SMB
SMB

Reputation: 55

Adding a Single Arrow with Arrowhead to a plot in ggplot2 using R

I have a PC, 64bit. Using ggplot 2 in Rstudio v0.98.953, current R update.

I am new to ggplot and limited proficiency in R. I have the following code:

# Simple Bar Plot for Multivariate OR by NVP quartile
dat <- data.frame(
  QUAR = factor(c("1","2","3","4"), levels=c("1","2","3","4")),
  aOR = c(1.00, 2.47, 3.33, 9.17),
  lowerCI = c(1.00, 1.09, 1.33, 3.20),
  upperCI = c(1.00, 5.60, 8.30, 26.0)
)
dat

library(ggplot2)
myplot = ggplot(data=dat, aes(x=QUAR, y=aOR, fill=QUAR)) + 
  geom_bar(colour="black", width=.8, stat="identity") + 
  scale_fill_manual(values=c("#e8e7e7", "#c3bfbf", "#908c8c", "#363434")) +
  guides(fill=FALSE) +
  xlab("XXX Quartile") + ylab("YYY") +
  geom_text(data=dat, aes(x=QUAR, y=aOR, label=round(aOR, 1)), vjust=-0.5) +
  coord_cartesian(ylim = c(0, 11)) +
  ggtitle("Graph")
myplot
# this gets rid of the grid line and background color  
plot (myplot)  
myplot2 = myplot + geom_errorbar(aes(ymin=lowerCI, ymax=upperCI), width=.1) +
       theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(), panel.background = element_blank(), axis.line = element_line(colour = "black"))
myplot2

enter image description here

This works fine, but I would like to add a single arrow to the 4th bar. You can see that the CI goes beyond the upper limit of the Y axis (which is set at 11) and I would like to just put a single arrowhead pointing up to indicate that the upper limit for the 4th bar goes beyond 11.

I've tried the arrows function - arrows(x0, y0, x1, y1, code=1), but have not been able to get it to run (returns with plot.new has not been called up or something like that).

Any thoughts?

Thanks!

Upvotes: 4

Views: 6625

Answers (1)

Josh O&#39;Brien
Josh O&#39;Brien

Reputation: 162321

geom_segment has an arrow argument that should help you here. Try something like this:

library(grid)  ## Needed for `arrow()`

myplot2 + geom_segment(aes(x=4, xend=4, y=10, yend=11), 
                           arrow = arrow(length = unit(0.5, "cm")))

enter image description here

Upvotes: 6

Related Questions