ggplot and two different geom_line(): the legend does not appear

爱⌒轻易说出口 提交于 2019-12-04 15:22:18

You could rbind them and use color

ruz$type <- "ruz"
dfr$val2 <- dfr$val2 * 100
dfr$type <- "dfr"
names(ruz) <- names(dfr)
df <- rbind(ruz, dfr)

ggplot(df, aes(date, val2, color = type), size = 1.5) + geom_line()

If you want to avoid combining the data.frames, you can do this:

ggplot() + 
  geom_line(data = ruz, aes(date, val1, color = "a"), size = 1.5) + 
  geom_line(data = dfr, aes(date, val2 * 100, color = "b"), size = 1.5) + 
  scale_color_manual(name = "Colors", 
                     values = c("a" = "blue", "b" = "red"))

In order to get a legend, you have to map something to color within aes. You can then use scale_color_manual to define the colors for the mapped character values. There are situations where this trick is easier and results in more readable code then reshaping/combining data.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!