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

时间:2016-04-19 12:25:09

标签: r plot ggplot2

我正在尝试为我的情节添加一个传奇,这就是我现在所拥有的:

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

我希望在情节的右侧看到一个传奇,但这是输出:

Code sample output

如何为这两个密度图添加图例?

2 个答案:

答案 0 :(得分:3)

这里的代码非常接近。你可以摆弄其余部分。

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)

enter image description here

答案 1 :(得分:1)

你可以这样做:

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

在绘制它们之前,你必须构建不错的数据帧。这是ggplot优势的关键:p。这里您的垂直线段不包含在图例中。如果您希望如此,则必须使用段的颜色美学和密度的填充美学(而不是像示例中那样的密度)。