Question

I want to plot a stacked bar plot with error bars. I have a data frame with five variables. Var1 contains the effects of treatments on three different species in Var2. The effects of treatments are given in variable value. Variable start and end contains the values for error bars. I want to plot a stacked bar plot in a way that orders of Var1 and Var2 should be same. Something like this:

This figure is just an example. Some example data:

Var1    Var2    value   start   end
Eff1    spe1    0.73    0.72    0.74
Eff2    spe1    0.25    0.24    0.26
Eff3    spe1    0.007   0.006   0.008
Eff1    spe2    0.69    0.68    0.7
Eff2    spe2    0   0   0
Eff3    spe2    0.3 0.29    0.31
Eff1    spe3    0.78    0.77    0.79
Eff2    spe3    0   0   0
Eff3    spe3    0.212   0.2 0.22

The values in table does not match to the figure above. Thank you for the suggestions.

Was it helpful?

Solution

df <- read.table(text="
Var1    Var2    value   ybegin  yend
Eff1    spe1    0.73    0.72    0.74
Eff2    spe1    0.25    0.24    0.26
Eff3    spe1    0.007   0.006   0.008
Eff1    spe2    0.69    0.68    0.7
Eff2    spe2    0   0   0
Eff3    spe2    0.3 0.29    0.31
Eff1    spe3    0.78    0.77    0.79
Eff2    spe3    0   0   0
Eff3    spe3    0.212   0.2 0.22", header = T)
str(df)

df[df$Var1 == "Eff2", "ybegin"] <- df[df$Var1 == "Eff2", "ybegin"] + df[df$Var1 == "Eff1", "value"]
df[df$Var1 == "Eff2", "yend"] <- df[df$Var1 == "Eff2", "yend"] + df[df$Var1 == "Eff1", "value"]
df[df$Var1 == "Eff3", "ybegin"] <- df[df$Var1 == "Eff3", "ybegin"] + df[df$Var1 == "Eff2", "ybegin"]
df[df$Var1 == "Eff3", "yend"] <- df[df$Var1 == "Eff3", "yend"] + df[df$Var1 == "Eff2", "yend"]

library(ggplot2)
dodge <- position_dodge(width = 0.9)
cols <- c("black", "white", "darkgrey") 
limits <- aes(ymax = yend , ymin = ybegin)
ggplot(df, aes(x = Var2, y = value, fill = Var1)) + geom_bar(stat="identity", color = "black") + 
  scale_fill_manual(values = cols) +
  geom_errorbar(limits, colour = "red", width = 1,  position = dodge) + 
  theme_bw() +
  theme(panel.grid.major = element_blank() ,panel.grid.minor = element_blank()) 

enter image description here

OTHER TIPS

In my opinion, a stacked barplot with errorbars isn't the best choice. For comparison an example with a dodged barplot with errorbars:

ggplot(df, aes(x=Var2, y=value, fill=Var1)) + 
  geom_bar(stat="identity", color="black", position=position_dodge(width = 0.9)) + 
  geom_errorbar(aes(ymax=yend, ymin=ybegin), width=0.6, position=position_dodge(width = 0.9)) + 
  theme_bw() +
  theme(panel.grid.major.x = element_blank(), panel.grid.minor = element_blank())

which results in: enter image description here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top