Home > Software engineering >  Legend using scale_linetype_manual results in identical lines in legend
Legend using scale_linetype_manual results in identical lines in legend

Time:08-04

I want to generate a plot that specifies that line 1 is a linear trend with a solid line and line 2 is a horizontal line with longdash line. Following tips enter image description here

The resulting legend in the plot shows both lines are "solid", but the cut-off is clearly a different linetype ("long-dash") in the plot (and in the code). Is there a way for the legend to reflect what the plot shows? Thanks.

CodePudding user response:

You can make the legend key a little wider so you can see the full length of the dash.

ggplot(
  data = mutate(mtcars, limit = 20),
  mapping = aes(x = hp, y = mpg)
)   
  theme_bw()   
  geom_point(color = "purple")   
  geom_smooth(
    aes(linetype = "linear trend"),
    method = "lm",
    formula = "y ~ x",
    se = FALSE,
    color = "black", # col = "dark green",
    size = 1
  )  
  #Add precision cut-off
  geom_hline(
    mapping = aes(yintercept = limit, linetype = "cut-off", alpha="cut-off"),
    color = "black", #color = "dark green",
    alpha = 0.5,
    size = 1,
    na.rm = TRUE
  )  
  scale_linetype_manual(
    name = NULL,
    values = c(
      "longdash",  #cut-off
      "solid"  #mean
    )) 
  theme(legend.key.width =unit(1.25, units = "cm"))
  • Related