Add legend to geom_line() graph in r

纵饮孤独 提交于 2019-12-03 10:22:52

ggplot needs aes to make a legend, moving colour inside aes(...) will build a legend automatically. then we can adjust the legend labels via scale_color_discrete:

ggplot()+
    geom_line(data=Summary,aes(y=Y1,x= X,colour="darkblue"),size=1 )+
    geom_line(data=Summary,aes(y=Y2,x= X,colour="red"),size=1) +
    scale_color_discrete(name = "Y series", labels = c("Y2", "Y1"))

As has been said, a color must be specified inside an aesthetic in order for there to be a legend. However, the color inside the aesthetic is actually just a label that then carries through to other layers. Setting custom colors can be done with scale_color_manual and the legend label can be fixed with labs.

ggplot(data=Summary)+
  geom_line(mapping=aes(y=Y1,x= X,color="Y1"),size=1 ) +
  geom_line(mapping=aes(y=Y2,x= X,color="Y2"),size=1) +
  scale_color_manual(values = c(
    'Y1' = 'darkblue',
    'Y2' = 'red')) +
  labs(color = 'Y series')

To provide a more compact answer which only uses a single geom call:

ggplot2 really likes long data (key-value pairs) better than wide (many columns). This requires you to transform your data prior to plotting it using a package like tidyr or reshape2. This way you can have a variable denoting color, inside your aes call, which will produce the legend.

For your data:

library(tidyr)
library(ggplot2)

plot_data <- gather(data, variable, value, -x)

ggplot(plot_data, aes(x = x, y = value, color = variable)) +
  geom_line() +
  scale_color_manual(values = c("firebrick", "dodgerblue")) 

You can then customize the legend via scale_color series of helpers.

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