nouse
nouse

Reputation: 3461

dodged barcharts in ggplot2

From this dataframe:

sums.f <- structure(list(variable = structure(c(5L, 4L, 3L, 2L, 1L, 5L, 
4L, 3L, 2L, 1L, 5L, 4L, 3L, 2L, 1L), .Label = c("T2", "T3", "T4", 
"T5", "T6"), class = c("ordered", "factor")), mean = c(589802.320933333, 
443125.114366667, 208689.6513, 121799.312326667, 135647.783493333, 
40333.3333333333, 66333.3333333333, 81333.3333333333, 34566.6666666667, 
12000, 5766.66666666667, 4433.33333333333, 29000, 27200, 58333.3333333333
), sd = c(184039.064728101, 104751.271302054, 97683.165688192, 
30441.5353531024, 96776.9417988552, 23028.9672658878, 63955.7138442949, 
41295.6817758629, 29566.2532853477, 20784.6096908265, 6622.93993127926, 
3950.10548382361, 20074.8598998847, 29858.3321704344, 55608.7523087268
), sem = c(106255.003562176, 60478.1746841967, 56397.4020053725, 
17575.4286306592, 55874.1933989178, 13295.7804501194, 36924.8486042183, 
23842.0729896636, 17070.0842932242, 12000, 3823.7561521508, 2280.59446441298, 
11590.2257671425, 17238.7161161536, 32105.7281147427), Group = c("D", 
"D", "C", "C", "B", "D", "D", "C", "C", "B", "D", "D", "C", "C", 
"B"), rep = c("A", "B", "C", "D", "E", "A", "B", "C", "D", "E", 
"A", "B", "C", "D", "E")), .Names = c("variable", "mean", "sd", 
"sem", "Group", "rep"), row.names = c(NA, 15L), class = "data.frame")

i want to plot three barcharts for each factor level in "variable", next to each other. This is usually done by "position="dodge", but in my example the barcharts end up being stacked. I tried to do several groupings by the column "rep", but thats not possible.

Here is what i tried:

ggplot(sums.f, aes(x=variable, y=mean)) +
  geom_bar(aes(fill=Group), width=0.6, position="dodge", stat="identity", col="black") +
  geom_errorbar(aes(ymin=mean, ymax=mean+sem), position="dodge", width=0.25)

enter image description here

So, the question is how to dodge the three charts for each variable.

Thank you.

Upvotes: 1

Views: 158

Answers (1)

David Robinson
David Robinson

Reputation: 78600

You need to add a group aesthetic that tells the graph to keep each bar separate. This could be as simple as a column of different numbers:

sums.f$index <- seq_len(nrow(sums.f))

At this point, adding group = index to the aes call will separate the bars:

ggplot(sums.f, aes(x=variable, y=mean, group = index)) +
  geom_bar(aes(fill=Group), position="dodge", stat="identity", col="black") +
  geom_errorbar(aes(ymin=mean, ymax=mean+sem), position="dodge")

Upvotes: 3

Related Questions