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

Can I fix overlapping dashed lines in a histogram in 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()

请注意,其中一条应该显示为虚线的线实际上是实线(值为 x = 4)。我认为这一定是因为它实际上是两条线 - 一条来自 3-4 条,一条来自 4-5 条。这些点是异相的,因此它们会产生一条实线。效果比较丑,前后不一致。

  1. 有什么方法可以解决这种重叠问题吗?
  2. 任何人都可以提出一种更有效的方法来澄清这两个类别之间的区别,而无需借助颜色吗?

非常感谢。

首先,我会推荐 theme_set(theme_bw())theme_set(theme_classic())(这会将背景设置为白色,这使得(更)容易看到灰色阴影)。

其次,您可以尝试类似 scale_linetype_manual(values=c(1,3)) 的操作——这不会完全消除您不满意的瑕疵,但它可能会使它们不那么突出,因为线型 3 比线型 2 更稀疏.

缺少绘制密度图(这对于小样本效果不佳,您的观众可能不熟悉),避开直方图的位置(这很丑陋),或以其他方式偏离直方图惯例,我想不出更好的解决方案。

一种可能性是使用 'hollow histogram',如 here:

所述
# 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()

如果要同时改变线型和填充,则需要先绘制直方图(可以填充)。将直方图的轮廓颜色设置为透明。然后添加 geom_step。使用 theme_bw 避免 'grey elements on grey background'

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()