两个数据系列覆盖在相同的条形图/直方图上

Dur*_*and 2 statistics r histogram bar-chart ggplot2

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

有没有一种方法R可以智能地覆盖条形,这样我就可以使用完全不透明的条形图,并且从来没有隐藏过视图的条形图?这是我目前的代码:

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))
Run Code Online (Sandbox Code Playgroud)

50%不透明条形码的代码输出

任何指针都非常感谢.

mne*_*nel 6

以长格式工作,然后position_dodge用来躲避重叠的箱子.如果你希望他们还是重叠的,那么你可以设置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)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

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

在此输入图像描述

或者你可以使用刻面,这意味着你的问题会消失,因为你不再过度绘图了

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

在此输入图像描述