r - 两个数据系列叠加在同一个条形图/直方图上

标签 r statistics ggplot2 histogram bar-chart

我正在使用 ggplot2,我需要在同一个直方图上显示两组数据,并且需要区分它们。目前,我只是将每个系列的颜色设置为 50% 的不透明度,这样我就可以看到隐藏在彼此后面的条形图,但这远非理想,看起来真的很难看,而且读起来很困惑。

有没有一种方法可以让 R 智能地覆盖条形图,以便我可以使用完全不透明的条形图,并且永远不会有条形图隐藏在 View 之外?这是我目前的代码:

library(ggplot2)
dat <- data.frame(a=sample(10, size=100, replace=T),
                  b=sample(10, size=100, replace=T))
ggplot(dat, aes(x=a), fill=rgb(1,0,0,0.5)) + geom_histogram()
                           + geom_histogram(aes(x=b), fill=rgb(0,0,1,0.5))

code output for 50% opaque bars

非常感谢任何指点。

最佳答案

以长格式工作,然后使用 position_dodge 来避开重叠的 bin。如果您希望它们仍然重叠,那么您也可以设置 alpha

例如

library(reshape2)
ldat <- melt(dat)


 # slight overlap
 ggplot(ldat, aes(x=value, colour = variable, fill = variable)) + 
    geom_histogram(position = position_dodge(width = 0.5), binwidth = 1, alpha =0.5)

enter image description here

# or the default value
ggplot(ldat, aes(x=value, colour = variable, fill = variable)) + 
  geom_histogram(position = 'dodge', binwidth = 1)

enter image description here

或者您可以使用分面,这将意味着您的问题消失了,因为您不再过度绘制了

ggplot(ldat, aes(x=value)) + 
  geom_histogram(binwidth=1,fill = 'grey', colour = 'black') +
  facet_grid(~variable)

enter image description here

关于r - 两个数据系列叠加在同一个条形图/直方图上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16005953/

相关文章:

r - glmnet 变量重要性 | `vip` 与 `varImp`

R fread data.table 速度不一致

r - 在 ggplot2 中的图表标题周围放置一个灰色框

r - 强制尺寸美观以适应给定的中断

regex - R正则表达式删除字母之间的撇号

machine-learning - 正态分布连续变量的概率计算

r - 错误概率函数

android - Google Play Developer Console 中的奇怪统计数据

r:在 ggplot 图中插入 ggtexttable()

r - 如何将绘图保存为磁盘上的图像?