I have the following data.frame
called df1
:
meanS meanQ1 meanQ7 meanQB SDS SDQ1 SDQ7 SDQB
A 0.0000000 18.5097329 82.979770 112.39874 0.0000000 15.7327272 14.8470696 57.4588193
B 0.8251663 1.5863240 6.113925 13.18822 1.1669613 0.9277886 0.6524881 3.3680380
C 4.7411325 16.6099939 40.202326 65.54109 1.9964880 9.0839058 11.7395347 15.3689217
D 5.5147541 11.3603839 62.658601 52.91574 1.8887582 7.0104244 7.7074550 12.1494890
E 1.0847299 28.1761223 31.865756 24.22025 0.3728842 10.2018362 5.6468526 8.9097609
Where the columns are the means of 4 conditions and the respective standard deviations (SD).
In order to generate multiple ggplot
bar plots (one for each row), I'm doing the following (based on this post):
df2 <- df1[,1:4]
library(data.table)
df2 <- data.table(t(df2), colnam = colnames(df2), df = "df2")
df2 <- melt(df2, id.vars = c("colnam", "df"))
df2[, sd := t(df1[,5:8])]
ggplot(df2, aes(x = colnam, y = value, fill = df, ymax = value + sd, ymin = value - sd)) +
geom_bar(position = "dodge", stat = "identity") +
facet_wrap(~variable, ncol = 2, scales = "free_y") +
geom_errorbar(position = position_dodge(width = 0.9), width=0.2)
My problem is that when I do this, the order of the bars is changed from (S, Q1, Q7,QB) to (Q1, Q7,QB, S).
Is there a way to correct this?