简体   繁体   English

R中具有ggplot2的自定义图例具有多个密度图

[英]Custom legend with ggplot2 in R having multiple density plots

I'm trying to add a legend to my plot, and here's what I have for now: 我正在尝试向图中添加图例,这是我现在拥有的:

require(ggplot2)
d1 = data.frame(rnorm(100, mean=5))
d2 = data.frame(rnorm(50, mean=7))
single_data = 5.5
max_y = max(max(density(d1[,1])$y), max(density(d2[,1])$y))
print(ggplot() + geom_density(aes(x=d1), colour='black', data=d1, kernel='gaussian', alpha=.1, fill='red') + 
        geom_density(aes(x=d2), colour="black", data=d2, kernel='gaussian', alpha=.1, fill='blue') + 
        geom_segment(aes(x=single_data, xend=single_data, y=0, yend=max_y), colour='blue') +
        xlab("Count") + ylab("Density") + ggtitle('Main Title') +
        theme(legend.position='right') +
        scale_color_manual(name = "Data",
                           labels = c(5, 7),
                           values = c('red', 'blue'))
)

I expect to see a legend on the right side of the plot, but here's the output: 我希望在该图的右侧看到一个图例,但这是输出:

代码样本输出

How can I add a legend for these two density plots? 如何为这两个密度图添加图例?

Here's the code that can come pretty close. 这是非常接近的代码。 You can fiddle with the rest. 您可以摆弄其余的东西。

library(ggplot2)
set.seed(9)
d1 = data.frame(d1 = rnorm(100, mean=5))
d2 = data.frame(d2 = rnorm(50, mean=7))
single_data = 5.5

xy <- data.frame(d1 = d1, d2 = d2)

library(tidyr)
xy <- gather(xy)

ggplot(xy, aes(x = value, fill = key)) +
  geom_density(kernel = "gaussian", alpha = 0.1) +
  geom_vline(xintercept = single_data)

在此处输入图片说明

You can do this: 你可以这样做:

require(ggplot2)
df <- data.frame(density=c(rnorm(50, mean=5), rnorm(50, mean=7)),
                 name=c(rep('d1', 50), rep('d2', 50)))

single_data = 5.5
max_y = max(max(density(d1[,1])$y), max(density(d2[,1])$y))

p1 <- ggplot(data=df) +
        geom_density(aes(x=density, group=name, colour=name, fill=name), kernel='gaussian', alpha=.5) + 
        geom_segment(aes(x=single_data, xend=single_data, y=0, yend=max_y), colour='blue') +
  scale_color_manual('Legend Name', labels=c('density 1', 'density 2'), values=c('blue', 'green')) +
  scale_fill_manual('Legend Name', labels=c('density 1', 'density 2'), values=c('blue', 'green')) +
        xlab("Count") + ylab("Density") + ggtitle('Main Title') +
        theme(legend.position='right')
p1

You have to build decent dataframes before ploting them. 在绘制它们之前,您必须先构建体面的数据框。 That's the key to the ggplot superiority :p. 这就是ggplot优势的关键:p。 Here you vertical segment is not included in the legend. 在这里,垂直线段不包括在图例中。 If you want it to be so, you have to use the color aesthetic for the segment and the fill aesthetic for the densities (instead of both for the densities as it is in the example). 如果希望如此,则必须对线段使用颜色美学,对密度使用填充美学(而不是像示例中那样对密度使用两种颜色)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM