ESmyth5988
ESmyth5988

Reputation: 518

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. For example, I would like to end up with a figure that looks like: Figure

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)

Upvotes: 4

Views: 4859

Answers (1)

DatamineR
DatamineR

Reputation: 9628

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

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

enter image description here

P.S.: the -.12 is used to get rid of the dodging effect to the arrows.

Upvotes: 6

Related Questions