我的数据框中有大量行(~100,000)的两组纬度和经度变量。我正在尝试制作一个连接这两组坐标的图(即从latitude1,longitude1到latitude2,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()
Run Code Online (Sandbox Code Playgroud)
我希望这些线在第一个经纬度坐标点处以蓝色开始,在第二个经纬度坐标点处以红色结束。
该ggforce方法似乎是解决您所要求问题的最佳方法。您的代码几乎就是您正在寻找的内容,但我认为您可能忽略了colour = stat(index)映射内的语句。我假设这index是一个geom_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()
Run Code Online (Sandbox Code Playgroud)
不过,请注意,因为您打算绘制很多线;如果你使用alpha =forgeom_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", size = 10, alpha = 0.1) +
scale_colour_gradient(low = "red", high = "green") +
coord_equal()
Run Code Online (Sandbox Code Playgroud)
或者,您可以使用箭头来指示结束位置,如下所示:
ggplot(example.df, aes(longitude.1, latitude.1)) +
geom_segment(aes(xend = longitude.2, yend = latitude.2),
arrow = arrow()) +
coord_equal()
Run Code Online (Sandbox Code Playgroud)
一个潜在的缺点是箭头可能会过分强调非常短的片段。
希望这可以帮助!
| 归档时间: |
|
| 查看次数: |
1380 次 |
| 最近记录: |