如何在 geom_segment 中创建带箭头的多行

How to create multiple lines with arrows in geom_segment

我正在尝试创建一个如下例所示的图表。也就是说,我希望添加指向 2019 年到 2021 年移动方向的箭头。

我有以下示例数据集:

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

我使用了下面的ggplot代码

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

创建以下ggplot

我正在努力弄清楚如何在点之间添加箭头。我尝试了以下代码,我基于 this Whosebug 讨论:

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

不幸的是,这会产生以下错误:

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

我很感激大家的任何建议。我可能只是对问题的措辞有误,但我还没有在 Whosebug 上找到关于这个特定问题的讨论。感谢您的帮助!

切换到 geom_path 您可以:

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