我正在使用ggplot从两个不同的数据帧创建两个重叠的密度。我需要为每种密度创建一个图例。
我一直试图关注这两篇文章,但仍然无法使其正常工作:
How to add legend to plot with data from multiple data frames
ggplot legends when plot is built from two data frames
我要执行的操作的示例代码:
df1 = data.frame(x=rnorm(1000,0))
df2 = data.frame(y=rnorm(2500,0.5))
ggplot() +
geom_density(data=df1, aes(x=x), color='darkblue', fill='lightblue', alpha=0.5) +
geom_density(data=df2, aes(x=y), color='darkred', fill='indianred1', alpha=0.5) +
scale_color_manual('Legend Title', limits=c('x', 'y'), values = c('darkblue','darkred')) +
guides(colour = guide_legend(override.aes = list(pch = c(21, 21), fill = c('darkblue','darkred')))) +
theme(legend.position = 'bottom')
是否可以手动创建图例?
还是我需要根据这篇文章重组数据?
Adding legend to ggplot made from multiple data frames with controlled colors
我对R还是很陌生,所以希望能避免将数据堆叠到单个数据帧中,因为它们是加权密度,因此也必须乘以不同的权重。
答案 0 :(得分:1)
与x
,y
,label
等不同,在使用密度几何时,color
美学 可以在{{ 1}}。为了完成您要寻找的东西,aes()
的美感需要转移到color
中,使您能够利用aes()
。在其中,您可以将scale_color_manual
更改为您喜欢的任何内容。
values=
由reprex package(v0.3.0)于2020-08-09创建