1

I have some problems plotting error bars on the plot, they seem to gather at the centre of 2 bars, rather than on the centre of each bar.

data <- data.frame(
  strain = rep(c("control", "7TM mutation"), each = 3), 
  compoundname = c("Diacetyl", "Benzaldehyde", "Octanol"),
  IO = c(0.932, 0.790, -0.546, -0.016, 0.708, -0.600), 
  sd = c(0.044, 0.073, 0.205, 0.130, 0.210, 0)
)

ggplot(data) +
  geom_bar( aes(x=compoundname, y=IO,fill= strain), stat="identity", alpha=0.5, position = 
  position_dodge()) +
  scale_fill_manual(values = c("grey","black")) +
  geom_errorbar( aes(x = compoundname, ymin=IO-sd, ymax=IO+sd), width=0.2, colour="black", 
  position = position_dodge(0.9))+
  theme_light() +
  xlab("Volatile Compound")+
  ylab("Olfactory Index")
 

What I obtained

camille
  • 16,432
  • 18
  • 38
  • 60
Tab83
  • 11
  • 1

1 Answers1

0

The issue is that you missed to add the group aesthetic to geom_errorbar, i.e. you have to tell ggplot that you want your errorbars grouped and dodged by strain. To this end add group=strain as an additional aesthetic:

library(ggplot2)

ggplot(data, aes(x = compoundname)) +
  geom_bar(aes(y = IO, fill = strain),
    stat = "identity", alpha = 0.5, position =
      position_dodge()
  ) +
  scale_fill_manual(values = c("grey", "black")) +
  geom_errorbar(aes(ymin = IO - sd, ymax = IO + sd, group = strain),
                width = 0.2, colour = "black",
                position = position_dodge(0.9)
  ) +
  theme_light() +
  xlab("Volatile Compound") +
  ylab("Olfactory Index")

As a second option you could make the aesthetics used for the bars global by moving them into ggplot(). This way the errorbars will automatically inherit the global grouping set via fill=strain:

ggplot(data, aes(x = compoundname, y = IO, fill = strain)) +
  geom_bar(
    stat = "identity", alpha = 0.5, position =
      position_dodge()
  ) +
  scale_fill_manual(values = c("grey", "black")) +
  geom_errorbar(aes(ymin = IO - sd, ymax = IO + sd),
    width = 0.2, colour = "black",
    position = position_dodge(0.9)
  ) +
  theme_light() +
  xlab("Volatile Compound") +
  ylab("Olfactory Index")
stefan
  • 90,330
  • 6
  • 25
  • 51