R ggplot2 连接散点图中的多条线

R ggplot2 Multiple Lines in Connected Scatterplot

我需要在连接的散点图中绘制多条线,但 运行 遇到了问题。我可以绘制一条线,但不能绘制另一条(或更多)。

代码

library(dplyr)
library(ggplot2)
library(ggrepel)
library(tidyr)

year<-c(2010,2011,2012,2013,2014,2015,2016,2017,2018,2019)

variableA1<-c(56,169,313,595,797,989,934,869,824,662)
variableB1<-c(0,0,5,12,23,44,73,71,78,103)

variableA2<-c(22,58,159,342,603,1021,1589,2071,2268,2044)
variableB2<-c(1,1,0,3,7,9,33,59,84,98)


data<-data.frame(year,variableA1,variableB1,variableA2,variableB2)

data %>% 
  ggplot(aes(x=variableA1, y=variableB1, label=year)) +
     geom_point(color="#333333") + 
     geom_text_repel() +
     geom_segment(color="#333333", 
                aes(
                    xend=c(tail(variableA1, n=-1), NA), 
                    yend=c(tail(variableB1, n=-1), NA)
                ),
                arrow=arrow(length=unit(0.3,"cm"))
                ) +
     geom_point(color="#a8a8a8") + 
     geom_text_repel() +
     geom_segment(color="#a8a8a8", 
                aes(
                    xend=c(tail(variableA2, n=-1), NA), 
                    yend=c(tail(variableB2, n=-1), NA)
                ),
                arrow=arrow(length=unit(0.3,"cm"))
                )

ggplot 图表

这并不是 ggplot2 的真正处理方式。

相反,您在同一列中定义两个系列的 x 和 y 坐标,并添加另一列指定这些值属于哪个数据系列。

编辑

还应为每个数据系列明确设置线段坐标(箭头):

data_points<-data.frame(year = year, varA = variableA1, varB = variableB1, series = "series1") %>%
  bind_rows(data.frame(year = year, varA = variableA2, varB = variableB2, series = "series2"))

data_lines<-data.frame(
    x = head(variableA1, n=-1),
    y = head(variableB1, n=-1),
    xend = tail(variableA1, n=-1),
    yend = tail(variableB1, n=-1),
    series = "series1") %>%
  bind_rows(
    data.frame(
      x = head(variableA2, n=-1), 
      y = head(variableB2, n=-1), 
      xend = tail(variableA2, n=-1),
      yend = tail(variableB2, n=-1), 
      series = "series2")
  )

data_points %>% 
  ggplot(aes(x=varA, y=varB, label=year, color=series)) +
  geom_point(color="#333333") + 
  geom_text_repel() +
  geom_segment(data = data_lines,
               aes(x = x, y = y, xend = xend, yend = yend, 
                   color = series, label=NA),
               arrow=arrow(length=unit(0.3,"cm"))
  ) +
  scale_color_manual( values = c('#333333', '#a8a8a8'))