在ggplot2中躲过了条形图

时间:2015-09-29 14:41:27

标签: r ggplot2

从这个数据框:

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

我想在“变量”中为每个因子级别绘制三个条形图,彼此相邻。这通常通过“position =”dodge“来完成,但在我的例子中,条形图最终被堆叠。我试图通过”rep“列进行多次分组,但那是不可能的。

这是我试过的:

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

所以,问题是如何为每个变量躲避三个图表。

谢谢。

1 个答案:

答案 0 :(得分:3)

您需要添加group美学,告诉图表保持每个条形分开。这可以像一列不同的数字一样简单:

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

此时,将group = index添加到aes来电将分隔条:

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