简体   繁体   English

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

[英]R - ggplot2 - Add arrow if geom_errorbar outside limits

I am creating a figure using ggplot and would like to use arrows to indicate where my error bars go beyond the defined axis. 我正在使用ggplot创建一个图形,并希望使用箭头指示我的误差条超出定义轴的位置。 For example, I would like to end up with a figure that looks like: 例如,我想得到一个看起来像这样的数字: 数字

I want R to determine which lower bounds are outside the defined chart range and to add a nice looking arrow (instead of my ugly paint added arrows). 我希望R确定哪些下限在定义的图表范围之外,并添加一个漂亮的箭头(而不是我的丑陋油漆添加箭头)。

I know there has to be a way to do this. 我知道必须有办法做到这一点。 Any ideas? 有任何想法吗? Here is my code to make the above graph without the arrows added by-hand: 这是我的代码,使上面的图形没有添加箭头:

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

What about this: first create a column to check if the values go beyond your range and if this is the case determine the length from the y-point to the border of the plot. 这个怎么样:首先创建一个列来检查值是否超出您的范围,如果是这种情况,则确定从y点到绘图边界的长度。

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

In the second step use this variable to add arrows with segment . 在第二步中,使用此变量添加带有segment箭头。 If there are also values going through the upper limit you can additionally use the other variable ULC_l to add further arrows. 如果还有值通过上限,您还可以使用其他变量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")))

在此输入图像描述

PS: the -.12 is used to get rid of the dodging effect to the arrows. PS:-. -.12用于摆脱对箭头的闪避效果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM