1

I am trying to create a graph that looks like the example below. Namely, I am looking to add arrows that point in the direction of movement from 2019 to 2021.

enter image description here

I have the following example dataset:

structure(list(jurisdiction = c("Alabama", "Illinois", "Nebraska", 
"Oklahoma", "Alabama", "Illinois", "Nebraska", "Oklahoma"), xvar = c(4.9, 
1.3, 3.4, 7.2, 3.2, 3.5, 4.7, 5.5), year = c("2021", "2021", 
"2021", "2021", "2019", "2019", "2019", "2019"), pair = c(1, 
7, 15, 19, 1, 7, 15, 19)), row.names = c(69L, 46L, 105L, 44L, 
1L, 10L, 22L, 28L), class = "data.frame")

I have used the following ggplot code

ggplot(dt,aes(x=xvar,y=reorder(jurisdiction, -pair),color=year))+
  geom_point()+
  geom_line(aes(group=pair))

to create the following ggplot

enter image description here

I am struggling to figure out how to add arrows between the points. I have tried the following code, which I based from this stackoverflow discussion:

geom_segment(data=reshape(dt,v.names="rh_percentage",idvar="jurisdiction",timevar="year",direction="wide"),
aes(x=rh_percentage.2019,xend=rh_percentage.2021,y=jurisdiction,yend=jurisdiction),size=2,
arrow=arrow(length=unit(0.5,"cm")))

This unfortunately produces the following error:

Error in FUN(X[[i]], ...) : object 'rh_percentage.2019' not found
In addition: Warning message:
In reshapeWide(data, idvar = idvar, timevar = timevar, varying = varying,  :
  some constant variables (xvar) are really varying

I would appreciate any suggestions folks have. I might just be phrasing the question wrong, but I haven't found a discussion of this particular issue on StackOverflow yet. Thanks for the help!

babybonobo
  • 89
  • 8

1 Answers1

2

Switching to geom_path you could do:

library(ggplot2)

ggplot(dt, aes(x = xvar, y = reorder(jurisdiction, -pair), color = year)) +
  geom_point() +
  geom_path(aes(group = pair), 
            arrow = arrow(ends = "first", length = unit(0.1, "inches")), 
            show.legend = FALSE, color = "grey65")

stefan
  • 90,330
  • 6
  • 25
  • 51
  • thank you so much, that worked perfectly. Not sure why I didn't think of geom_path, but that's a great solution (I guess it's one of my less utilized ggplot functions). Have a great evening! – babybonobo Apr 26 '22 at 20:50
  • 1
    Haha. Yeah. Me neither. But if geom_line does not work as desired I always give geom_path a try as it "connects the observations in the order in which they appear in the data" while "geom_line() connects them in order of the variable on the x axis.". – stefan Apr 26 '22 at 20:54