关于ggplot2:R:是否可以绘制带有颜色渐变的geom_segment线? (或者还有另一种方式强调开始还是结束?)

R: is it possible to draw a geom_segment line with a colour gradient? (or is there another way to emphasize start vs end?)

对于数据框中的大量行,我有两组纬度和经度变量(?100,000)。我正在尝试使用geom_segment绘制一个连接这两套坐标(即从纬度1,经度1到纬度2,经度2的?100,000条线)的图,并使用非常低的alpha来使线透明,因为有太多线。
我想强调这些线条的起点和终点,我认为最好的方法是从头到尾都有一个颜色渐变(比如说绿色到红色)。

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

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

这是5行的一些示例数据(但实际上我有大约100,000,因此在计算上应该有一定效率):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
 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()

这产生了以下五行:
enter image description here

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


ggforce方法似乎是您要问的最佳方法。 您的代码几乎就是您想要的代码,但是我认为您可能忽略了映射内的colour = stat(index)语句。 我假设indexgeom_link()在幕后计算以插入颜色的统计量。

1
2
3
4
5
6
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()

enter image description here

不过要提个警告,因为您打算绘制多条线。 如果对geom_link()使用alpha =,则可以清楚地看到行的分段:

1
2
3
4
5
6
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()

enter image description here

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

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

enter image description here

潜在的弊端是箭头可能会过分强调非常短的段。

希望这可以帮助!