使用ggplot在图例中包含所有图层 [英] Having all layers in the legend with ggplot

查看:122
本文介绍了使用ggplot在图例中包含所有图层的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎样才能制作一个图例来表示我的图中绘制的所有曲线?目前,第一层(基于颜色美学)产生了一个自动图例,但另一层(黑色曲线代表所有观测中的价格变量密度)未包含在该图例中。

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

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

解决方案

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



像这样:

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






注意:您可以通过指定手动色阶来对颜色进行额外的控制:

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


how could I make a legend representing all the curves that are plotted in my graph ? Presently, an automatic legend is generated for the first layer (based on the "colour" aesthetic), but the other layer (the black curve representing the density of "price" variable across all observations) in not contained in this legend.

I conceive that my question comes certainly from an incomplete understanding of the concepts behing ggplot package.

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

解决方案

The principle in ggplot2 is that each aesthetic gets mapped to a scale. So, if you want to include a layer in the colour scale, you need to map that layer to colour.

Like this:

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


Note: You can take additional control over the colours by specifying a manual colour scale:

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)
    )

这篇关于使用ggplot在图例中包含所有图层的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆