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

cou*_*rix 3 r histogram ggplot2

我想使用来自两个不同条件(下例中的 A 和 B)的数据创建直方图。geom_histogram我想在 R 中使用同一图中绘制两个分布。

然而,对于条件 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")
Run Code Online (Sandbox Code Playgroud)

r2e*_*ans 5

可视化的替代方案,不取代 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"')
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

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

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

在此输入图像描述

对于透视图,position = "stack"默认值显示“A”,直方图明显改变。

在此输入图像描述