Home > Blockchain >  scale_linetype_manual is not working or shown on legend in R, why?
scale_linetype_manual is not working or shown on legend in R, why?

Time:05-15

I would like to have two linotypes (one solid and one dashed) and having it shown on the legend as well (this doesn't show either), I have tried the code below but lines aren't changing, also I have tried adding scale_linetype_manual(values=c("solid", "dashed")) before the scale_colour manual, and does not do any effect.

 data<- data.frame(
          Date=(1:13),
          A=c(1.12,2.78,2.08,1.55,0.67,0.98,1.43,0.42,0.30,0.82,0.51,0.23,0.44),
          B= c(0.10,0.07,0.04,0.05,0.10,0.08,0.12,0.05,0.02,0.11,0.06,0.05,0.11),
          C= c(9.97,6.94,10.87,9.69,12.27,11.27,10.42,10.97,9.15,10.59,11.64,8.86,8.47))
    
    LINES <- c("A" = "solid", "B" = "dashed")
    
    ggplot(data)    
      geom_line(aes(Date, A, color = "A"))  
      geom_point(aes(Date, A)) 
      geom_line(aes(Date, B*10, color="B")) 
      geom_point(aes(Date, B*10)) 
      scale_y_continuous(sec.axis = sec_axis(~./100, name= expression(paste("B", "(", mu, "M)")))) 
      scale_color_manual(name = "", values = c("A" = "black", "B" = "black"), labels=c(A ~ (mu~M)), (B ~ (mu~M))) 
      scale_linetype_manual(values=LINES) 
      theme_classic() 
      ylab(bquote(A ~ (mu~M))) 
      xlab("")

enter image description here

CodePudding user response:

A general advice that you will hear again and again when working with gggplot2 is that get your data in long format. It makes it really easy to plot the data when it is in long format.

We remove the C column which is not required here and use pivot_longer to get data in long format, specify linetype and color as column name and draw line and point plot for them.

library(tidyverse)

data %>%
  select(-C) %>%
  pivot_longer(cols = -Date) %>%
  ggplot(aes(Date, value, color = name, linetype = name))    
  geom_line()  
  geom_point()   
  scale_y_continuous(sec.axis = sec_axis(~./100, 
          name= expression(paste("B", "(", mu, "M)"))))   
  scale_linetype_manual(values= LINES)  
  theme_classic() 
  ylab(bquote(A ~ (mu~M))) 
  xlab("")

enter image description here

  • Related