Home > Blockchain >  DotDash and TwoDash linetypes not working in ggplot2 R
DotDash and TwoDash linetypes not working in ggplot2 R

Time:05-05

I am trying to plot twodash and dotdash, but I only get dash as the output.

set.seed(111)
var <- rep(c("SP1","SP2","AB1","AB2"), times = 5)
var.val <- rnorm(20,5,1)
level <- rep(c(100,200,300,400), each = 5)

df <- data.frame(var, var.val, level)

ggplot(df, aes(x = level, y = var.val, col = var, group = var))   
  geom_point(aes(fill = var), colour="white",pch=21, size=4, stroke = 1,
             alpha = 0.7, data = df[df$var %in% c("SP1", "SP2"),])  
  theme_classic()   
  geom_smooth(data = df[df$var %in% c("SP1", "SP2"),],
              method = "lm", formula = y ~ x, alpha = 0.2)  
  geom_smooth(data = df[!df$var %in% c("SP1", "SP2"),],
              method = "lm", formula = y ~ x, se = FALSE, linetype = 2 )    
  scale_linetype_manual(values = c("dotdash", "twodash","solid", "solid"))   
  scale_colour_manual(values = c("black","black","red","blue"))

enter image description here

CodePudding user response:

Try setting linetype as part of the aesthetic in your ggplot call:

ggplot(df, aes(x = level, y = var.val, col = var, group = var, linetype = var))   # set linetype
  geom_point(aes(fill = var), colour="white",pch=21, size=4, stroke = 1,
             alpha = 0.7, data = df[df$var %in% c("SP1", "SP2"),])  
  theme_classic()   
  geom_smooth(data = df[df$var %in% c("SP1", "SP2"),],
              method = "lm", formula = y ~ x, alpha = 0.2)  
  geom_smooth(data = df[!df$var %in% c("SP1", "SP2"),],
              method = "lm", formula = y ~ x, se = FALSE)    
  scale_linetype_manual(values = c("dotdash", "twodash","solid", "solid"))   
  scale_colour_manual(values = c("black","black","red","blue"))

enter image description here

  • Related