[英]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绘制一个连接这两套坐标(即从latitude1,longitude1到latitude2,longitude2的 〜100,000条线 )的图,并使用非常低的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)
语句。 我假设index
是geom_link()
在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()
不过要提一个警告,因为您打算绘制多条线。 如果对geom_link()
使用alpha =
, 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", 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()
潜在的弊端是箭头可能会过分强调非常短的段。
希望这可以帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.