【问题标题】:How to insert a legend in density plot with qplot in R如何在 R 中使用 qplot 在密度图中插入图例
【发布时间】:2016-10-10 20:53:51
【问题描述】:

我对 R 完全陌生,想在下面的qplot 绘图函数中插入一个简单的彩色框图例,将每个分布标识为“data.1”和“data.2” (来自ggplot2 包):

> V1 <- matrix(unlist(rnorm(200,-0.2,1)))
> V2 <- matrix(unlist(rnorm(200,0.3,4)))
> m <- data.frame(V1,V2)
> qplot(V1, main="Observed distr.", data=m,
geom='density',xlab="x",ylab="count",fill=I('green'), alpha=I(.5)) +
geom_density(aes(V2),data=m,fill='red', alpha=I(.5))

我找到了ggplot 的解决方案,但没有找到qplotgeom='density' 的解决方案。曲线绘制得很好,但没有出现图例。
我会接受任何能给我提供透明度、标记轴、标题和彩色框图例的密度图的解决方案。谢谢。

【问题讨论】:

  • 恕我直言:忘记qplot,使用ggplotlibrary(tidyverse);ggplot(m %&gt;% gather, aes(value, fill = key)) + geom_density(alpha = .5) + scale_fill_manual(values = c("green", "red"), labels = c("V1" = "myV1"))。我想这将是他们无论如何都要走的路in the future“示例中 qplot() 的使用已大大减少。这与 ggplot2 书的第二版一致,它消除了 qplot() 的支持ggplot() 的。”
  • @lukeA:是的,我开始看到这一点。我完成了qplot。谢谢。

标签: r ggplot2 legend


【解决方案1】:

正如someone 所说,“ggplot 喜欢 'long' 格式的数据:即每个维度对应一列,每个观察对应一行”。所以我们meltdata.frame

require(ggplot2)
require(data.table)
set.seed(10) # this is so you get the same numbers from rnorm.
m <- data.frame(V1 = matrix(unlist(rnorm(200, -0.2, 1))),
                V2 = matrix(unlist(rnorm(200, 0.3, 4))))

m <- melt(m) # This comes from data.table, yet, many alt. ways to achieve this
head(m)
  variable       value
1       V1 -0.18125383
2       V1 -0.38425254
3       V1 -1.57133055
4       V1 -0.79916772
5       V1  0.09454513
6       V1  0.18979430

ggplot(data = m, aes(value, fill = variable)) +
  geom_density(alpha = 0.5)

【讨论】:

  • 谢谢你。正是我需要的。干杯。
猜你喜欢
  • 2023-03-28
  • 1970-01-01
  • 2015-09-27
  • 2015-02-20
  • 1970-01-01
  • 2020-06-19
  • 2011-11-30
  • 1970-01-01
  • 2012-11-08
相关资源
最近更新 更多