有没有办法在不调整透明度的情况下在 R 中显示重叠的直方图?

Is there a way to show overlapping histograms in R without adjusting transparency?

objective是为了显示重叠的直方图,但我想避免使用 alpha 调整以使颜色保持明亮。

有没有办法在不调整 alpha arg 的情况下做到这一点?

目标是显示如下所示的颜色:

hist(rnorm(mean=10, n = 1000), col='blue')
hist(rnorm(mean=11, n = 1000), col='red', add=T)

但也显示重叠区域,如图所示

hist(rnorm(mean=10, n = 1000), col='blue')
hist(rnorm(mean=11, n = 1000), col=rgb(1,0,0,0.5), add=T)

没有完全解决透明度的类似问题:

How to create black and white transparent overlapping histograms using ggplot2?

我可以接受密度和使用其他图形包(例如 lattice、ggplot2 等)。

编辑: 我希望填充图并且交叉区域是不同的颜色(例如红色和蓝色相交的紫色)。

使用 ggplot2geom_density 的解决方案。

library(ggplot2)
library(tidyr)

# create data
set.seed(1234)
df <- data.frame(x = rnorm(1000, 10), y = rnorm(1000, 11)) %>% 
  gather(key, value) # use tidyr::gather to convert from wide to long format

ggplot(df, aes(value, colour = key)) +
  geom_density(show.legend = F) +
  theme_minimal() +
  scale_color_manual(values = c(x = "red", y = "blue"))

# use 'adjust' to adjust density estimation
ggplot(df, aes(value, colour = key)) +
  geom_density(show.legend = F, adjust = .5) +
  theme_minimal() +
  scale_color_manual(values = c(x = "red", y = "blue"))

直方图

由于 alpha 不是选项,除了使用密度之外,您还可以将直方图堆叠在一起,尽管我更喜欢密度,因为它们更容易比较。

# using stacked histograms
ggplot(df, aes(value, fill = key)) +
  geom_histogram(show.legend = F) +
  theme_minimal() +
  scale_fill_manual(values = c(x = "red", y = "blue"))
#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

我想出了一个使用层的概念来解决这个问题。本质上,我在没有 alpha 的情况下放下红色,在下面添加蓝色层,然后通过 alpha 调整再次放回红色,以将重叠区域保持在我想要的对比度(即它保持紫色)。

one <- rnorm(mean=10, n = 1000)
two <- rnorm(mean=11, n = 1000)
hist(one, col='blue', main='Bright colors, visible overlap')
hist(two, col='red', add=T)
hist(one, col='blue', add=T)
hist(two, col=rgb(1,0,0,0.5), add=T)

也适用于 ggplot:

qplot(one, fill=I('blue'))+
  geom_histogram(aes(two), fill=I('red'))+
  geom_histogram(aes(one), fill=I('blue'))+
  geom_histogram(aes(two), fill=I('red'), alpha=I(0.5))

如果您不坚持重叠,那么您可以考虑使用 ggplot 的 "dodge" 定位选项并排绘制直方图的条形图。例如:

# generate data, some Normal and Gamma variates with the same mean & SD
set.seed(137)
rd <- data.frame(
  n=rnorm(1000, mean=6.0, sd=4.243), 
  g=rgamma(1000, shape=2, scale=3)
)

# convert the data frame to "tall" format
tall.rd <- stack(rd)

# make the plot
ggplot(tall.rd) + geom_histogram(
  aes(values,..density..,colour=ind, fill=ind),
  bins=20,position="dodge"
)