R - ggplot2 - 如果geom_errorbar超出限制,则添加箭头

时间:2015-02-09 17:17:24

标签: r ggplot2

我正在使用ggplot创建一个数字,并希望使用箭头指示我的误差线超出定义轴的位置。例如,我想得到一个看起来像这样的数字: Figure

我希望R确定哪些下界在定义的图表范围之外,并添加一个漂亮的箭头(而不是我添加的丑陋油漆箭头)。

我知道必须有办法做到这一点。有任何想法吗?这是我的代码,无需手工添加箭头即可生成上图:

#generate data
myData<-data.frame(ALPHA=round(runif(60,.5,.8),2),
                   error=round(runif(60,.05,.15),2),
                   formN=rep(1:5,12),
                   Cat=c(rep("ELL",30),rep("SWD",30)),
                   grade=rep(c(rep(3,5),rep(4,5),rep(5,5),rep(6,5),rep(7,5),rep(8,5)),2)
                   )
myData$LCL<-myData$ALPHA-myData$error
myData$UCL<-myData$ALPHA+myData$error

#set error outside of range for example
myData[myData$Cat=="ELL" & formN==1,"LCL"]<-0

library(ggplot2)
ggplot(myData, aes(x=formN, y=ALPHA, colour=Cat)) + 
  geom_errorbar(aes(ymin=LCL, ymax=UCL), width=.4, position=position_dodge(.5)) +
  geom_point(position=position_dodge(.5), size=2) +
  labs(x="Form", y="Alpha", title="TITLE") +
  geom_line(position=position_dodge(.5), size=.3) +
  coord_cartesian(ylim=c(.3, 1)) + 
  facet_wrap(~grade, ncol=3)

1 个答案:

答案 0 :(得分:2)

这个怎么样:首先创建一个列以检查值是否超出您的范围,如果是这种情况,则确定从y点到绘图边界的长度。

library(dplyr)
myData_m <- myData %>% mutate(LCL_l = ifelse(LCL < .3, ALPHA - .3, NA), UCL_l = ifelse(UCL > 1, 1 - ALPHA, NA))

在第二步中,使用此变量添加带segment的箭头。如果还有值超过上限,您还可以使用其他变量ULC_l添加更多箭头。

ggplot(myData_m, aes(x=formN, y=ALPHA, colour=Cat)) + 
    geom_errorbar(aes(ymin=LCL, ymax=UCL), width=.4, position=position_dodge(.5)) +
    geom_point(position=position_dodge(.5), size=2) +
    labs(x="Form", y="Alpha", title="TITLE") +
    geom_line(position=position_dodge(.5), size=.3) +
    coord_cartesian(ylim=c(.3, 1)) + 
    facet_wrap(~grade, ncol=3) + 

    geom_segment(aes(x = formN - .12, xend = formN - .12, y = ALPHA, yend = ALPHA - LCL_l), arrow = arrow(length = unit(myData_m$LCL_l, "cm")))

enter image description here

P.S。:-.12用于消除对箭头的闪避效果。