R语言 为什么ggplot2中的“dodge”命令对我不起作用?

rn0zuynd  于 2023-04-09  发布在  其他
关注(0)|答案(1)|浏览(137)

这里有点像R新手。我试图创建一个条形图,其中有三个单独的条来表示对照组,治疗组和两者组合的正确答案之和,但dodge参数似乎不起作用。我将在这里附上我的R代码。

ggplot(correct.data3, aes(x = Question)) +
  geom_bar(aes(y = Both, fill = "Both"), position = 'dodge', 
                stat = "identity") +
  geom_bar(aes(y = Control, fill = "Control"), position = 'dodge', 
               stat = "identity") +
  geom_bar(aes(y = Treatment, fill = "Treatment"), position = 'dodge', 
               stat = "identity") +
  labs(title = "Correct Responses",
       y = "Number of Correct Responses",
       fill = "Treatment Group") +
  theme_bw()

我想使用ggplot2创建一个条形图,x阅读Q1,Q2,Q3,Q4,每个问题都有三个条形代表对照组和治疗组的正确答案。我尝试使用dodge参数,但条形似乎重叠。我如何解决这个问题?

vddsk6oq

vddsk6oq1#

这不是ggplot2position_dodge的工作方式。对于position_dodge,您需要一个包含类别的列,这些类别应该显示为“隐藏”条,而不是三个单独的列。要实现这一点,请使用例如tidyr::pivot_longer将数据整形为长或整洁的格式。
使用一些假随机示例数据:

library(ggplot2)

set.seed(123)

correct.data3 <- data.frame(
  Question = paste0("Q", 1:4),
  Both = sample(1:10, 4),
  Control = sample(1:10, 4),
  Treatment = sample(1:10, 4)
)

correct.data3 |>
  tidyr::pivot_longer(-Question, names_to = "cat", values_to = "n") |>
  ggplot(aes(x = Question)) +
  geom_col(aes(y = n, fill = cat), position = "dodge") +
  labs(
    title = "Correct Responses",
    y = "Number of Correct Responses",
    fill = "Treatment Group"
  ) +
  theme_bw()

相关问题