0

Sort of a R rookie here. I'm trying to create a bar chart with three separate bars to represent the sum of correct answers for the control, treatment and both combined but the dodge argument doesn't seem to be working. I'll attach my R code here.

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()

I wanted to use ggplot2 to create a bar chart with the x-axis reading Q1, Q2, Q3, Q4 and for each question to have three bars representing the correct responses for both, control and treatment groups. I tried using the dodge argument but the bars seemingly overlap. How can I solve this?

kjetil b halvorsen
  • 1,206
  • 2
  • 18
  • 28
Kat
  • 1
  • 2

1 Answers1

2

That's not how ggplot2 and position_dodge works. For position_dodge you need one column containing the categories which should be displayed as "dodged" bars not three separate columns. To achieve that reshape your data to long or tidy format using e.g. tidyr::pivot_longer.

Using some fake random example data:

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()

stefan
  • 90,330
  • 6
  • 25
  • 51