用颜色渐变绘制一条 geom_segment 线? (或者有另一种强调开始与结束的方法吗?)

Draw a geom_segment line with a colour gradient? (or is there another way to emphasize start vs end?)

我有两组纬度和经度变量,用于我的数据框中的大量行 (~100,000)。我正在尝试绘制连接这两组坐标的图(即,从 latitude1,longitude1latitude2,longitude2 的约 100,000 条线), 使用 geom_segment, 使用非常低的 alpha 使线条透明,因为线条太多了。

我想强调这些线条的起点和终点,我认为最好的方法是从头到尾有一个颜色渐变(假设是绿色到红色)。

是否可以绘制带有颜色渐变的 geom_segment 线?如果不是,您是否知道用这么多行强调开始与结束的另一种方法?

(我意识到它最终可能看起来很乱,因为有太多行,但我怀疑其中很多都是同一个方向..)

这是一些 5 行的示例数据(但实际上我有 ~100,000,所以计算效率应该有点高):

 example.df <- as.data.frame(matrix(c(1,435500,387500,320000,197000,
                                      2,510500,197500,513000,164000,
                                      3,164500,40500,431000,385000,
                                      4,318500,176500,316000,172000,
                                      5,331500,188500,472000,168000),
                                      nrow=5, ncol=5, byrow = TRUE))
  colnames(example.df) <- c("ID","longitude.1","latitude.1",
                            "longitude.2","latitude.2")

 library(ggforce)
 ggplot(example.df, aes(longitude.1, latitude.1))+
 geom_link(aes(x=longitude.1, y=latitude.1,
               xend=longitude.2, yend=latitude.2, 
               alpha=0.5), col="black")+
 coord_equal()

这会产生以下五行:

我希望这些线在第一个经纬度坐标点处以蓝色开始,在第二个经纬度坐标点处以红色结束。

ggforce 方法似乎是解决您所问问题的最佳方法。您的代码几乎就是您要查找的代码,但我认为您可能忽略了映射中的 colour = stat(index) 语句。我假设 indexgeom_link() 在后台计算以插入颜色的统计数据。

ggplot(example.df, aes(longitude.1, latitude.1))+
  geom_link(aes(x = longitude.1, y = latitude.1,
                xend = longitude.2, yend = latitude.2, 
                colour = stat(index)), lineend = "round") +
  scale_colour_gradient(low = "red", high = "green") +
  coord_equal()

提醒一句,鉴于您打算绘制多条线;如果你对 geom_link() 使用 alpha =,你可以清楚地看到行的分段:

ggplot(example.df, aes(longitude.1, latitude.1))+
  geom_link(aes(x = longitude.1, y = latitude.1,
                xend = longitude.2, yend = latitude.2, 
                colour = stat(index)), lineend = "round", size = 10, alpha = 0.1) +
  scale_colour_gradient(low = "red", high = "green") +
  coord_equal()

或者,您可以使用箭头指示结束位置,如下所示:

ggplot(example.df, aes(longitude.1, latitude.1)) +
  geom_segment(aes(xend = longitude.2, yend = latitude.2),
               arrow = arrow()) +
  coord_equal()

一个潜在的缺点是箭头可能会过分强调非常短的片段。

希望对您有所帮助!