【问题标题】:R ggplot2 Multiple Lines in Connected ScatterplotR ggplot2 连接散点图中的多条线
【发布时间】:2020-05-15 13:29:01
【问题描述】:

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

代码

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 图表

【问题讨论】:

    标签: r ggplot2 scatter-plot


    【解决方案1】:

    这不是真正使用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'))
    

    【讨论】:

    • 谢谢。这似乎更接近我正在寻找的东西,但我如何避免这是一个连续图?上图中,第一个系列的 2019 年与第二个系列的 2010 年相连。我需要它们是两条“单独的”行。
    • 你说得对@Rahul,线段的开始和结束坐标仍然是关闭的。它们需要以不同的方式指定。我稍后再看看。
    • 现在看看。我编辑了答案以包含箭头段的正确坐标。