Home > database >  How to create multiple lines with arrows in geom_segment
How to create multiple lines with arrows in geom_segment

Time:04-27

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!

CodePudding user response:

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

  • Related