R中具有ggplot2的自定义图例具有多个密度图 [英] Custom legend with ggplot2 in R having multiple density plots

查看:63
本文介绍了R中具有ggplot2的自定义图例具有多个密度图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试向图中添加图例,这是我现在拥有的:

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)

这篇关于R中具有ggplot2的自定义图例具有多个密度图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆