Two ways of adding arrows

Can someone school me on the best way to add arrows to ggplot? I have a little reprex below in which I draw an arrow. The first method is copied from Statology. The second method is from the R Graphics Cookbook. The former seems a little easier. The latter, well, the R Graphics Cookbook is the bible as far as I'm concerned.

Can anyone tell me the difference in the two approaches? Any pros and cons?

t <- tibble(x = c(1,2,3),y=c(3,2,2))

t |> ggplot(aes(x=x,y=y)) + geom_point() +
  geom_segment(aes(x=1, y=2, xend=2, yend=2),
               arrow = arrow(length=unit(.5, 'cm')))


t |> ggplot(aes(x=x,y=y)) + geom_point() +
  annotate("segment", x=1, y=2, xend=2, yend=2,
         arrow = arrow())

Created on 2023-12-07 with reprex v2.0.2

I would say a fundamental difference is that geom_segment() is a mapping between data and a geom, here we're "cheating" by using fixed data in aes(x=1) instead of of a column name aes(x= x). Whereas annotate() is explicit about the fact that we're not drawing data, we're annotating on top of it with fixed values.

I don't think there is an explicit pro or con to these approaches, but the annotate() feels more natural to add an arrow at a fixed point, whereas I would keep the geom_segment() for cases where x and y are given by the data.

1 Like

That definitely helps me understand.

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.