R-ggplot2-如果geom_errorbar超出限制,则添加箭头 [英] R - ggplot2 - Add arrow if geom_errorbar outside limits
问题描述
我正在使用ggplot创建图形,并希望使用箭头指示错误条超出定义轴的位置.例如,我想得到一个看起来像这样的图:
I am creating a figure using ggplot and would like to use arrows to indicate where my error bars go beyond the defined axis. For example, I would like to end up with a figure that looks like:
我希望R确定哪些下限不在定义的图表范围之内,并添加一个漂亮的箭头(而不是我的难看的油漆添加的箭头).
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).
我知道必须有一种方法可以做到这一点.有任何想法吗?这是我的代码,上面的图形没有手工添加箭头:
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)
推荐答案
这是怎么回事:首先创建一列以检查值是否超出了您的范围,如果是这种情况,请确定从y点到目标点的长度.情节的边界.
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.
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
添加更多箭头.
In the second step use this variable to add arrows with segment
. If there are also values going through the upper limit you can additionally use the other variable ULC_l
to add further arrows.
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")))
P.S.:-.12
用于消除箭头的闪避效果.
P.S.: the -.12
is used to get rid of the dodging effect to the arrows.
这篇关于R-ggplot2-如果geom_errorbar超出限制,则添加箭头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!