谁能解释为什么创建具有两个条件的直方图显示 R 中的分布不正确?

Can anyone explain why creating a histogram with two conditions shows incorrect distribution in R?

我想用来自两个不同条件(下例中的 A 和 B)的数据创建直方图。我想在 R.

中使用 geom_histogram 在同一个图中绘制两个分布

但是,对于条件 A,似乎显示了整个数据集的分布(而不是仅显示 A)。

在下面的示例中,显示了三种情况:

  1. 绘制 A 和 B
  2. 仅绘制 A
  3. 仅绘制 B

对比1)和2)就会发现A的分布不一样

谁能解释为什么会出现这种情况以及如何解决这个问题?

set.seed(5)

# Create test data frame 
test <- data.frame(
  condition=factor(rep(c("A", "B"), each=200)),
  value =c(rnorm(200, mean=12, sd=2.5), rnorm(200, mean=13, sd=2.1))
)

# Create separate data sets
test_a <- test[test$condition == "A",]
test_b <- test[test$condition == "B",]

# 1) Plot A and B
ggplot(test, aes(x=value, fill=condition)) +
  geom_histogram(binwidth = 0.25, alpha=.5) +
  ggtitle("Test A and AB")

# 2) Plot only A
ggplot(test_a, aes(x=value, fill=condition)) +
  geom_histogram(binwidth = 0.25, alpha=.5) +
  ggtitle("Test A")

# 3) Plot only B
ggplot(test_b, aes(x=value, fill=condition)) +
  geom_histogram(binwidth = 0.25, alpha=.5) +
  ggtitle("Test B")

这些地块堆叠在 A+B 地块中。所以 A 条从 B 条的顶部开始。此外,轴上的缩放比例不同。垃圾箱也可能有不同的端点。

所以,是的,A+B 图显示了总分布。填充可帮助您查看 A 和 B 各自的贡献。

如果要叠加两个地块,请使用:

ggplot(mapping = aes(x=value, fill=condition)) +
    geom_histogram(data = test_a, binwidth = 0.25, alpha=.5) +
    geom_histogram(data = test_b, binwidth = 0.25, alpha=.5) +
    ggtitle("Test A and AB") 

可视化的替代方案,而不是取代 MichaelDewar 的答案:

ggab <- ggplot(test, aes(x=value, fill=condition)) +
  geom_histogram(binwidth = 0.25, alpha=.5, position = "identity") +
  ggtitle("Test A and AB") +
  xlim(5, 20) +
  ylim(0, 13)

# 2) Plot only A
gga <- ggplot(test_a, aes(x=value, fill=condition)) +
  geom_histogram(binwidth = 0.25, alpha=.5) +
  ggtitle("Test A") +
  xlim(5, 20) +
  ylim(0, 13)

# 3) Plot only B
ggb <- ggplot(test_b, aes(x=value, fill=condition)) +
  geom_histogram(binwidth = 0.25, alpha=.5) +
  ggtitle("Test B") +
  xlim(5, 20) +
  ylim(0, 13)

library(patchwork) # solely for a quick side-by-side-by-side presentation
gga + ggab + ggb + plot_annotation(title = 'position = "identity"')

此可视化的关键是将 position="identity" 添加到第一个历史记录(其他不需要它)。

或者,可以使用 position="dodge"(最好在控制台上查看,在这个小快照上有点困难)。

对于视角,position = "stack",默认情况下,显示“A”和明显改变的直方图。