点意味着通过箱线图组的中心垂直对齐,而不是在各自的箱线图上

问题描述 投票:0回答:1

我正在使用截至 2024 年 3 月 17 日的最新版本的 R、R Studio、reshape2 和 ggplot2。

我有这个代码:

# Create long-form data
Apples.Long <- Apples[, 2:8]
Apples.Long <- melt(Apples.Long)
names(Apples.Long) <- c("Characteristic", "Score")

# Create boxplots
ggplot(data = Apples.Long, mapping = aes(x = Characteristic, y = Score, fill = Characteristic)) +
  geom_boxplot() +
  stat_boxplot(geom = "errorbar") +
  stat_summary(fun = "mean", shape = 20) +
  labs(x = NULL, caption = "Figure 1: Boxplots of characteristics") +
  theme_bw()

创建了这个数字:

Single group of boxplots with means plotted as dots

我想创建另一个图形,但将数据分成两组。我有这段代码来尝试做到这一点:

# Create long-form data
Apples.Long <- Apples[, 2:9]
Apples.Long <- melt(Apples.Long)
names(Apples.Long) <- c("Quality", "Characteristic", "Score")

# Create boxplots
ggplot(data = Apples.Long, mapping = aes(x = Quality, y = Score, fill = Characteristic)) +
  geom_boxplot() +
  stat_boxplot(geom = "errorbar") +
  stat_summary(fun = "mean", shape = 20) +
  labs(x = NULL, caption = "Figure 4: Boxplots of characteristics by quality") +
  theme_bw()

创建了这个数字:

Two groups of boxplots with means plotted as dots

为什么均值的点沿着组的中心对齐?我该如何修复它?任何帮助表示赞赏。我在网上找不到任何相关信息,人工智能也没有多大帮助。

r ggplot2 boxplot
1个回答
0
投票

您需要在您的积分中添加

position_dodge2()

library(ggplot2)

ggplot(mpg, aes(x = factor(year), y = hwy, fill = class)) +
  geom_boxplot() +
  stat_boxplot(geom = "errorbar") +
  stat_summary(fun = "mean", shape = 20, position = position_dodge2(width = 0.75)) +
  theme_bw()

© www.soinside.com 2019 - 2024. All rights reserved.