多层ggplot的自定义图例 [英] Custom legend for multiple layer ggplot
问题描述
我正在尝试为 ggplot 获取自定义图例,其中数据来自两个单独的数据框.请参阅下面的最小可重现示例.
I'm trying to get a custom legend for a ggplot with data coming from two separate data frames. See below for a minimum reproducible example.
我想要完成的是有一个描述色带填充、黑线和红线的图例.
What I'm trying to accomplish is to have a legend describing the ribbon fill, the black line, and the red line.
require(ggplot2)
x=seq(1,10,length=100)
data=data.frame(x,dnorm(x,mean=6.5,sd=1))
names(data)=c('x','new.data')
x.ribbon=seq(1,10,length=20)
ribbon=data.frame(x.ribbon,
dnorm(x.ribbon,mean=5,sd=1)+.01,
dnorm(x.ribbon,mean=5,sd=1)-.01,
dnorm(x.ribbon,mean=5,sd=1))
names(ribbon)=c('x.ribbon','max','min','avg')
ggplot()+geom_ribbon(data=ribbon,aes(ymin=min,ymax=max,x=x.ribbon),fill='lightgreen')+
geom_line(data=ribbon,aes(x=x.ribbon,y=avg),color='black')+
geom_line(data=data,aes(x=x,y=new.data),color='red')+
xlab('x')+ylab('density')
推荐答案
不是设置 colour
和 fill
,而是使用几何美学映射它们>aes
然后使用 scale_xxx_manual
或 scale_xxx_identity
.
Instead of setting colour
and fill
, map them using the geometry aesthetics
aes
and then use scale_xxx_manual
or scale_xxx_identity
.
例如
ggplot()+geom_ribbon(data=ribbon,aes(ymin=min,ymax=max,x=x.ribbon,fill='lightgreen'))+
geom_line(data=ribbon,aes(x=x.ribbon,y=avg,color='black'))+
geom_line(data=data,aes(x=x,y=new.data,color='red'))+
xlab('x')+ylab('density') +
scale_fill_identity(name = 'the fill', guide = 'legend',labels = c('m1')) +
scale_colour_manual(name = 'the colour',
values =c('black'='black','red'='red'), labels = c('c2','c1'))
请注意,您必须指定 guide = 'legend'
以强制 scale_..._identity
生成图例.
Note that you must specify guide = 'legend'
to force scale_..._identity
to produce a legend.
scale_...manual
您可以为值传递一个命名向量——名称应该是您在调用 geom_...
时调用的颜色然后你可以很好地标记.
scale_...manual
you can pass a named vector for the values -- the names should be what you called the colours within the calls to geom_...
and then you can label nicely.
这篇关于多层ggplot的自定义图例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!