How to adapt legend to fit the figure

The data and code are in the following. How to change the legend, so that level 2 and level 4 are shown as dashed lines? For example, change level 2 and level 4 to dashed lines in the legend, rather than show as solid lines. Thanks for your help.

library(ggplot2)

a = data.frame(value=c(-3.65,-2.37,-3.43,-3.49,-3.58,-5.49,-2.72,-5.05,-5.11,-5.31,
-7.31,-5.37,-2.43,-2.32,-1.79,-1.49,1.27,-7.05,-3.11,-7.96),
group=c(1, 2, 3, 4, 5, 1, 2, 3, 4, 5,
1, 2, 3, 4, 5, 1, 2, 3, 4, 5),
level=c(1, 1, 1, 1, 1, 2, 2, 2, 2, 2,
3, 3, 3, 3, 3, 4, 4, 4, 4, 4))

color.plate = c('blue','blue','red','red')
orders = c('level 1','level 2','level 3','level 4')

pa = ggplot()+ theme_bw()+
geom_line(data=subset(a,level==1),aes(x=group,y=value,color='level 1'))+
geom_line(data=subset(a,level==2),aes(x=group,y=value,color='level 2'),linetype='dashed')+
geom_line(data=subset(a,level==3),aes(x=group,y=value,color='level 3'))+
geom_line(data=subset(a,level==4),aes(x=group,y=value,color='level 4'),linetype='dashed')+
xlab('Group')+ ylab('Value')+
scale_color_manual('',values=color.plate, limits=orders)+
theme(panel.grid=element_blank(),legend.position = c(.7, .85))+
guides(colour = guide_legend(nrow = 1))
print(pa)

Does this help?

library(ggplot2)

dataset <- data.frame(value = c(-3.65, -2.37, -3.43, -3.49, -3.58,
                                -5.49, -2.72, -5.05, -5.11, -5.31,
                                -7.31, -5.37, -2.43, -2.32, -1.79,
                                -1.49, 1.27, -7.05, -3.11, -7.96),
                      group = rep.int(x = 1:5,
                                      times = 4),
                      level = rep(x = 1:4,
                                  each = 5))

ggplot(data = dataset,
       mapping = aes(x = group,
                     y = value)) +
  geom_line(mapping = aes(group = level,
                          colour = factor(x = level),
                          linetype = factor(x = level))) +
  scale_colour_manual(name = "Level",
                      values = c("blue", "blue", "red", "red")) +
  scale_linetype_manual(name = "Level",
                        values = c("solid", "dashed", "solid", "dashed")) +
  labs(x = "Group",
       y = "Value")

Created on 2019-07-08 by the reprex package (v0.3.0)

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.