我可以在ggplot2的直方图中修复重叠的虚线吗?

use*_*246 3 r histogram overlap ggplot2

我正在尝试在ggplot2中绘制两个重叠分布的直方图。不幸的是,图形必须是黑白的。我尝试用不同的灰色阴影和透明度来表示这两个类别,但是结果却不尽如人意。我尝试将轮廓添加到具有不同线型的条形,但这产生了一些奇怪的结果。

require(ggplot2)
set.seed(65)
a = rnorm(100, mean = 1, sd = 1)
b = rnorm(100, mean = 3, sd = 1)
dat <- data.frame(category = rep(c('A', 'B'), each = 100),
              values = c(a, b))

ggplot(data = dat, aes(x = values, linetype = category, fill = category)) +
        geom_histogram(colour = 'black', position = 'identity', alpha = 0.4, binwidth = 1) +
        scale_fill_grey()
Run Code Online (Sandbox Code Playgroud)

直方图

请注意,应显示为虚线的一行实际上是实线(x值为4)。我认为这一定是因为它实际上是两条线-一条来自3-4条,另一条来自4-5条。这些点异相,因此它们会产生一条实线。效果非常难看且不一致。

  1. 有什么办法可以解决此重叠问题?
  2. 有人可以提出一种更有效的方法来澄清两个类别之间的差异,而无需诉诸颜色吗?

非常感谢。

Hen*_*rik 6

一种可能性是使用“空心直方图”,描述在这里

# assign your original plot object to a variable 
p1 <- ggplot(data = dat, aes(x = values, linetype = category, fill = category)) +
  geom_histogram(colour = 'black', position = 'identity', alpha = 0.4, binwidth = 0.4) +
  scale_fill_grey()
# p1

# extract relevant variables from the plot object to a new data frame
# your grouping variable 'category' is named 'group' in the plot object
df <- ggplot_build(p1)$data[[1]][ , c("xmin", "y", "group")]

# plot using geom_step
ggplot(data = df, aes(x = xmin, y = y, linetype = factor(group))) +
  geom_step()
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

如果要同时改变线型和填充,则需要先绘制直方图(可以填充)。将直方图的轮廓颜色设置为透明。然后添加geom_step。使用theme_bw以避免“灰色背景灰色元素”

p1 <- ggplot() +
  geom_histogram(data = dat, aes(x = values, fill = category),
                 colour = "transparent", position = 'identity', alpha = 0.4, binwidth = 0.4) +
  scale_fill_grey()

df <- ggplot_build(p1)$data[[1]][ , c("xmin", "y", "group")]
df$category <- factor(df$group, labels = c("A", "B"))

p1 +
  geom_step(data = df, aes(x = xmin, y = y, linetype = category)) +
  theme_bw()
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明