【问题标题】:dodged barcharts in ggplot2ggplot2中闪避的条形图
【发布时间】:2015-09-29 14:41:26
【问题描述】:

从此数据框:

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)

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

谢谢。

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    您需要添加一个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")
    

    【讨论】:

    • 谢谢。我现在明白了为什么“rep”列在团体美学中不起作用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-03
    • 1970-01-01
    相关资源
    最近更新 更多