【问题标题】:Add a legend form geom_area in a density plot在密度图中添加图例形式 geom_area
【发布时间】:2018-05-14 19:36:46
【问题描述】:

我有以下图表。我想添加一个图例来解释密度中的灰色区域。有什么建议么?

这里的代码:

dd <- density(x, y, , na.rm = TRUE)
dd <- data.frame(x=dd$x,y=dd$y )

ggplot(dd, aes(x,y)) + 
 geom_line(color="black") + xlim(range(0, 45)) +
 geom_area(data = subset(dd, x >41), color="grey", fill = "grey")  +
 scale_x_discrete(limits=seq(from=0, to=45, by =5),
  labels=c("45", "40" , "35" , 
  "30", "25","20","15" , "10" , "5" , "Election")) + theme_minimal() +
 labs(title="Local Election", y="Density", x="Distance to the election(in 
  Months)") 

【问题讨论】:

    标签: r ggplot2 legend


    【解决方案1】:

    您需要为您的geom_area() 添加美感,如下所示:

    geom_area(data = subset(dd, x > 41), aes(fill = "x>41"))
    

    这样就可以实现你想要的了,但是颜色不会是灰色的,要改变颜色,你需要使用scale_fill_manual():

    ggplot() + .... + scale_fill_manual(values = c("x>41"="grey"))
    

    【讨论】:

    • 这项工作。谢谢。但是我还得把层geom_area里面的参数fill="grey"去掉,只留下geom_area的aes。非常感谢!
    • 如果答案对您有帮助,您能否接受它,以便面临相同问题的人知道该解决方案适用于该问题。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-26
    • 2011-11-30
    • 2021-06-24
    • 2021-01-11
    • 2019-06-21
    • 2015-11-08
    • 2018-01-08
    相关资源
    最近更新 更多