在ggplot2中的条形图中的一个组上创建误差线

时间:2014-05-28 08:32:47

标签: r ggplot2

我的数据中有两组,其中一组是固定数量且没有错误。我把这个组的标准偏差设为0.另一组是通过实验获得的并且有错误。我试图并排获得两组的酒吧但只想在一组上显示错误条。

以下是我的数据的子集

> dput(miniDF)
structure(list(meanVal = c(0.141142140910031, 0.123590465669207, 
0.107997372347094, 0.0942024597244465, 0.0820416407495106, 0.071353688041151, 
0.0619844689599558, 0.0537895165007547, 0.0466354169758515, 0.0404003706604038, 
0.158461397159066, 0.153053253758612, 0.138918096515527, 0.125843921455302, 
0.110345396211753, 0.0787109795360732, 0.0618074624835807, 0.0449341121897361, 
0.0363718842110094, 0.0291184151867377), sdVal = c(0, 2.86100521766632e-09, 
4.69695882560463e-09, 5.79859596041863e-09, 6.38047156294103e-09, 
6.60009718207142e-09, 6.57241274422449e-09, 6.3807059656363e-09, 
6.08482995661066e-09, 5.72736892254484e-09, 0, 0, 0, 0, 0, 0, 
0, 0, 0, 0), week = structure(c(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 
9L, 10L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L), .Label = c("Week 1", 
"Week 2", "Week 3", "Week 4", "Week 5", "Week 6", "Week 7", "Week 8", 
"Week 9", "Week 10", "Week 11", "Week 12", "Week 13", "Week 14", 
"Week 15", "Week 16", "Week 17", "Week 18", "Week 19", "Week 20", 
"Week 21"), class = "factor"), group = structure(c(2L, 2L, 2L, 
2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L), .Label = c("q", "qOpt"), class = "factor"), cluster = structure(c(1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L), .Label = c("1", "2", "3", "4", "5", "6", "7", "8", 
"9", "10"), class = "factor")), .Names = c("meanVal", "sdVal", 
"week", "group", "cluster"), row.names = c(1L, 2L, 3L, 4L, 5L, 
6L, 7L, 8L, 9L, 10L, 211L, 212L, 213L, 214L, 215L, 216L, 217L, 
218L, 219L, 220L), class = "data.frame")

情节的代码是,

limits <- aes(ymax = meanVal + sdVal, ymin = meanVal - sdVal)
dodge <- position_dodge(width=0.9)
p <- ggplot(miniDF, aes(fill=group, y=meanVal, x=cluster)) +
  geom_bar(position=dodge, stat="identity") +
  geom_errorbar(position=dodge,limits, width=0.25) +
  facet_wrap(~week,ncol=5)

enter image description here

我想要的是仅在组qOpt(蓝色)而不是组q上获得错误栏。我尝试在geom_errorbar函数中仅使用具有qOpt组的子集,但它弄乱了错误栏的位置,我无法将其置于蓝色条上。我很感激任何建议。感谢。

2 个答案:

答案 0 :(得分:3)

我能找到的最简单的解决方案就是

miniDF$sdVal[miniDF$group == 'q'] <- NA
p

enter image description here

答案 1 :(得分:2)

解决方法是使用geom_errorbar()内的数据子集,然后将x值设置为1.225(计算为1 + 0.9 / 4(闪避的宽度))。

dodge <- position_dodge(width=0.9)
ggplot(miniDF, aes(fill=group, y=meanVal, x=cluster)) +
      geom_bar(stat="identity",position=dodge) +
      geom_errorbar(data=subset(miniDF, group=="qOpt"),
               aes(x=1.225,ymax = meanVal + sdVal, ymin = meanVal - sdVal),width=0.25) +
      facet_wrap(~week,ncol=5)

enter image description here