r - 多层 ggplot 的自定义图例

标签 r ggplot2

我正在尝试为 ggplot 获取自定义图例,其中数据来自两个单独的数据帧。请参阅下面的最小可重现示例。

我想要完成的是有一个图例来描述带状填充、黑线和红线。

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

enter image description here

最佳答案

不要设置颜色填充,而是使用几何美学来映射它们 aes,然后使用 scale_xxx_manualscale_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'))

enter image description here

请注意,您必须指定 guide = 'legend' 才能强制 scale_..._identity 生成图例。

scale_...manual 您可以传递值的命名向量 - 名称应该是您在调用 geom_... 时所调用的颜色然后你就可以很好地标记了。

关于r - 多层 ggplot 的自定义图例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18394391/

相关文章:

r - 错误: installation of package ‘rgl’ had non-zero exit status

regex - 使用正则表达式拆分字符串并将其存储到数据框中

r - 如何更改 ggplot2 图例的标题?

r - r中的人口金字塔密度图

r - 如何使用 gg密度 叠加总密度和组密度

r - 具有时间序列线图的 tweenr/gganimate

r - grepl 排除模式之前的一组单词

sqlite - UNIX 将大型 csv 导入 SQLite

r - 具有新默认颜色的 ggplot2 几何图形

r - 在行尾绘制标签