-1

I've been trying to plot two line graphs, one dashed and the other solid. I succeeded in doing so in the plot area, but the legend is problematic.

I looked at posts such as Changing the line type in the ggplot legend , but I can't seem to fix the solution. Where have I gone wrong?

library(ggplot2)
year <- 2005:2015
variablea <- 1000:1010
variableb <- 1010:1020
df = data.frame(year, variablea, variableb)

p <- ggplot(df, aes(x = df$year)) +
  geom_line(aes(y = df$variablea, colour="variablea", linetype="longdash")) + 
  geom_line(aes(y = df$variableb, colour="variableb")) + 
  xlab("Year") +
  ylab("Value") + 
  scale_colour_manual("", breaks=c("variablea", "variableb")
                      , values=c("variablea"="red", "variableb"="blue")) + 
  scale_linetype_manual("", breaks=c("variablea", "variableb")
                      , values=c("longdash", "solid"))

p

enter image description here

Notice that both lines appear as solid in the legend.

Community
  • 1
  • 1
wwl
  • 2,025
  • 2
  • 30
  • 51

1 Answers1

3

ggplot likes long data, so you can map linetype and color to a variable. For example,

library(tidyverse)

df %>% gather(variable, value, -year) %>% 
  ggplot(aes(x = year, y = value, colour = variable, linetype = variable)) + 
  geom_line()

Adjust color and linetype scales with the appropriate scale_*_* functions, if you like.

alistaire
  • 42,459
  • 4
  • 77
  • 117