使用ggplot在图例中包含所有图层

时间:2012-11-15 09:42:40

标签: r ggplot2 legend

如何制作代表我的图表中绘制的所有曲线的图例?目前,为第一层生成自动图例(基于“颜色”美学),而在该图例中未包含另一层(表示所有观察中“价格”变量密度的黑色曲线)。

我认为我的问题肯定来自于对ggplot包的概念的不完全理解。

ggplot(diamonds) + 
  geom_density(aes(x = price, y = ..density.., colour = cut)) +
  geom_density(aes(x = price,y = ..density..))

enter image description here

1 个答案:

答案 0 :(得分:8)

ggplot2中的原则是每个美学都被映射到一个尺度。因此,如果您想要在colour比例中包含图层,则需要将该图层映射到colour

像这样:

ggplot(diamonds, aes(x=price)) + 
  geom_density(aes(colour = cut)) +
  geom_density(aes(colour="Overall"), size=1.5)

enter image description here


注意:您可以通过指定手动色标来进一步控制颜色:

ggplot(diamonds, aes(x=price)) + 
  geom_density(aes(colour = cut)) +
  geom_density(aes(colour="Overall"), size=1.5) +
  scale_colour_manual(
    limits=c("Overall", levels(diamonds$cut)),
    values=c("black", 2:6)
    )

enter image description here

相关问题