如何重塑数据以在 R 中创建多变量箱线图的各个方面

How to reshape data to create facets of boxplots of multiple variables in R

我想为我的数据创建多个方面的箱线图,以说明在不同条件下存在的每种化学物质的数量。

我有两个分类变量,M1 和 M2,它们的值分别为 "small, medium, large" 和 "low, medium, high"。我希望这些构成 3x3 小平面网格的基础。

然后我有 8 种化学物质 A-H,它们采用数值,我想要每个面上的每种化学物质的箱线图。

我制作了一个 3x3 的多面网格,但每个网格上只有一种化学物质。

编辑(从答案中获取的数据)我的数据看起来像生成的数据:

set.seed(1234)

n <- 100
M1 <- sample( c("small", "medium", "large"), n, TRUE)
M2 <- sample( c("low", "medium", "high"), n, TRUE)
tmp <- matrix(sample(100, 8*n, TRUE), ncol = 8)
colnames(tmp) <- LETTERS[1:8]

df <- data.frame(M1, M2)
df <- cbind(df, tmp)
rm(M1, M2, tmp)

我的剧情代码:

df %>%
  ggplot(aes(x = M1, y = A, fill = M1)) +
  geom_boxplot() +
  theme_minimal() +
  facet_grid(M2 ~ M1)

我想我需要重塑我的数据,以便 y = 'measure' 在我做多面箱线图之前,但我不确定如何

我想要一个 3x3 的分面网格,这样左下角对应 "small"、"low",右上角对应 "large"、"high",每种化学物质 A-H 的每个面上都有 8 个箱线图。

我希望每个方面的 y 轴是一个数值度量,x 轴是离散标签 A-H(对于 8 个箱线图)。对于整个 3x3 网格,(顶部)x 轴将是 3 个标签,小、中、大,(右)y 轴将是 3 个标签,低、中、高?

使用包 reshape2、函数 melt 重塑数据。然后使用interaction定义框组。

long <- reshape2::melt(df, id.vars = c("M1", "M2"))

ggplot(long, aes(x = M1, y = value, group = interaction(M1, M2), fill = M2)) +
  geom_boxplot() +
  theme(axis.text.x = element_text(angle = 30, hjust = 1)) +
  facet_wrap( ~ variable, scales = "free")

回复评论里的要求,看看是不是你的意思

ggplot(long, aes(x = variable, y = value, group = interaction(M1, variable), fill = M2)) +
  geom_boxplot() +
  facet_grid(M1 ~ M2, scales = "free")

测试数据创建代码。

我已经强迫 M2 考虑因素以便正确排序图例。

set.seed(1234)

n <- 100
M1 <- sample( c("small", "medium", "large"), n, TRUE)
M2 <- sample( c("low", "medium", "high"), n, TRUE)
M2 <- factor(M2, levels = c("low", "medium", "high"))
tmp <- matrix(sample(100, 8*n, TRUE), ncol = 8)
colnames(tmp) <- LETTERS[1:8]

df <- data.frame(M1, M2)
df <- cbind(df, tmp)
rm(M1, M2, tmp)