问题描述
我试图从一个ggplot获得一个自定义的图例,数据来自两个独立的数据框。请参阅下面的重现性示例。
我试图完成的是有一个图例来描述色带填充,黑线和红线。 / b>
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。色带,平均值= 5,sd = 1) - 。01,
dnorm(x.ribbon,mean = 5,sd = 1))
names(ribbon)= c('x.ribbon', ''最大'''最小'''平均')
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。数据),color ='red')+
xlab('x')+ ylab('density')
不是设置 Eg 请注意,您必须指定 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. Instead of setting Eg Note that you must specify 这篇关于R:多层ggplot的自定义图例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! color
和 fill
,使用几何美学
aes
将它们映射,然后使用 scale_xxx_manual
或 scale_xxx_identity
。
ggplot()+ geom_ribbon(data = ribbon,aes(ymin = min,ymax = max,x = x.ribbon,fill ='lightgreen') )+
geom_line(data = data,aes(x = x,y = avg,color ='black')) new.data,color ='red'))+
xlab('x')+ ylab('density')+
scale_fill_identity(name ='the fill',guide ='legend',labels = c('m1'))+
scale_colour_manual(name ='the color',
values = c('black'='black','red'='red'),labels = c ('c2','c1'))
guide ='legend'
来强制比例_..._ identity $ c
scale _... manual
您可以为值传递一个命名向量 - 名称应该是您呼叫 geom _...
内的颜色,然后您可以很好地标注。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
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'
to force scale_..._identity
to produce a legend.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.