简体   繁体   English

将图例添加到由多个不同数据帧构成的ggplot中

[英]Add a legend to a ggplot constructed from multiple different data frames

I have the following code: 我有以下代码:

  year_2001_2003 <- df[(df[,"year"]==2001)|(df[,"year"]==2002) | (df[,"year"]==2003),]

  top_wmaxc <- year_2001_2003[year_2001_2003$w_maxc > quantile(year_2001_2003$w_maxc, 0.90), ]
  top_wmaxb <- year_2001_2003[year_2001_2003$w_maxb > quantile(year_2001_2003$w_maxb, 0.90), ]
  top_wmaxa <- year_2001_2003[year_2001_2003$w_maxa > quantile(year_2001_2003$w_maxa, 0.90), ]

  top_wminc <- year_2001_2003[year_2001_2003$w_minc > quantile(year_2001_2003$w_minc, 0.90), ]
  top_wminb <- year_2001_2003[year_2001_2003$w_minb > quantile(year_2001_2003$w_minb, 0.90), ]
  top_wmina <- year_2001_2003[year_2001_2003$w_mina > quantile(year_2001_2003$w_mina, 0.90), ]



  ggplot(year_2001_2003, aes(wkd_ind, assaults)) + geom_line( ) +
    geom_point(data=top_wmaxc, size = 4, color="yellow") +
    geom_point(data=top_wmaxb, size = 4, color="orange") + 
    geom_point(data=top_wmaxa, size = 4, color="red") +

    geom_point(data=top_wminc, size = 4, color="darkblue") +
    geom_point(data=top_wminb, size = 4, color="blue") + 
    geom_point(data=top_wmina, size = 4, color="lightblue") +

    facet_grid(.~year, scale="free") 

This produces the correct graph with the correct colors. 这将生成具有正确颜色的正确图形。 However, I am not sure how to add a legend that captures these colors. 但是,我不确定如何添加可捕获这些颜色的图例。

I have tried something like: 我已经尝试过类似的东西:

scale_colour_manual(values=c("yellow","orange","red", "darkblue", "blue", "lightblue"))

but it doesn't show up in the graph 但它没有显示在图中

在此处输入图片说明

I found a hack job way of doing this. 我发现了一种破解工作的方法。 Not sure if there's an easier way: 不知道是否有更简单的方法:

 ggplot(year_2001_2003, aes(wkd_ind, assaults)) + geom_line( ) +
    geom_point(data=top_wmaxc, size = 4, aes(color="p1")) +
    geom_point(data=top_wmaxb, size = 4, aes(color="p2")) + 
    geom_point(data=top_wmaxa, size = 4, aes(color="p3")) +

    geom_point(data=top_wminc, size = 4, aes(color="p4")) +
    geom_point(data=top_wminb, size = 4, aes(color="p5")) + 
    geom_point(data=top_wmina, size = 4, aes(color="p6")) +

    scale_colour_manual(name = "Line Color", 
          values=c(p1="yellow", p2="orange", p3="red", p4="purple", p5="blue", p6="lightblue")) + 

    facet_grid(.~year, scale="free") 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM