Home > database >  How to manually change the ggplot2 legend to include vlines?
How to manually change the ggplot2 legend to include vlines?

Time:09-28

I've spent a bit of time on this from one rabbit hole to another. I would like to plot this data.


df <- data.frame(value = c(80,75,50,60,5,91,68,50,40,50),
                 event = c("a","b","c","d","e","a","b","c","d","e"), cell = c("A","A","A","A","A","B","B","B","B","B"))


This is as close as I have gotten to the plot I would like :

lines <- data.frame(intercepts = c("b","d"), names = c('treatment1','treatment2'))

ggplot(df, aes(x=event , y=value, group = cell, color =cell))   
  geom_line(aes(linetype=cell), size =1)  
  geom_point(aes(shape=cell), size = 2)  
  theme(panel.grid = element_blank(), 
        legend.key = element_rect(fill="white"),
        legend.title = element_blank(),
        panel.background = element_blank()) 
  geom_vline(data = lines, aes(xintercept = intercepts, color = names, linetype = names))  
  scale_color_manual(values = c("A" = "red", "B" = "blue", "treatment1" = "green", "treatment2" = "purple"))  
  scale_linetype_manual(values = c("A" = "solid", "B" = "solid", "treatment1" = "dashed","treatment2"="dashed"))  
  scale_shape_manual(values = c("A" = 18, "B" = 20, "treatment1" = 1, "treatment2"= 1)) 

Ggplot

The only issue is the legend does not look like the plot lines. A and B should look like this enter image description here in the legend, while treatment 1 and treatment 2 should be vertical, dashed, and of their respective colors.

CodePudding user response:

I'm not sure but please check it out. Please let me know if linetype for B needed to be solid or etc.

ggplot(df, aes(x=event , y=value, group = cell, color =cell))   
  geom_line(aes(linetype=cell), size =1)  
  geom_point(aes(shape=cell), size = 2)  
  theme(panel.grid = element_blank(), 
        legend.key = element_rect(fill="white"),
        legend.title = element_blank(),
        panel.background = element_blank()) 
  geom_vline(data = lines, aes(xintercept = intercepts, color = names, linetype = names), show.legend = F)  
  scale_color_manual(values = c("A" = "red", "B" = "blue", "treatment1" = "green", "treatment2" = "purple"),
                     guide = guide_legend(override.aes = list(
                       linetype = c(1,3,3,3), #HERE
                       shape = c(19, 17, NA, NA)
                     )))  
  guides(shape = "none", linetype = "none")

enter image description here

  • Related