繁体   English   中英

ggplot2:如何根据比例梯度更改元素的渲染/绘图顺序?

[英]ggplot2: how to change render/plot order of elements according to scale gradient?

我想知道:

a)什么决定了元素在 ggplot2 图中的呈现顺序?

b)如何根据变量或渐变色标来影响元素的绘图顺序?

上下文:我想可视化道路网络数据的连续变量(例如交通流量)。 重要的是,高值线最后绘制(以便它们出现在低值线的顶部),以使图清晰易读。 目前,默认似乎以随机顺序绘制线条。

下面是一个使用道路长度作为变量的示例,预期输出将按其值的顺序绘制道路线,即首先是灰线,然后是红灰线,然后是较深的红线,依此类推。

示例数据:

library(GISTools)
library(sf)
library(ggplot2)

data(newhaven)

ggplot() +
  geom_sf(data = st_as_sf(roads, "lines"), aes(col = LENGTH)) +
  scale_colour_gradient(low = "grey", high = "red")

纽黑文道路数据

这是一个放大图,可以很好地说明问题所在:灰色道路覆盖了红色道路。 但是,我想要实现的是最后绘制红色道路(因为它具有更大的长度值)。

ggplot() +
  geom_sf(data = st_as_sf(roads, "lines"), aes(col = LENGTH, size = 3)) +
  scale_colour_gradient(low = "grey", high = "red") +
  coord_sf(xlim = c(557000, 560000), ylim = c(178000, 180000)) + 
  annotate(geom = "curve", x = 558000, y = 178500, xend = 558850, yend = 179150, curvature = -.3, arrow = arrow(length = unit(3, "mm")))

放大纽黑文道路数据

通常,ggplot 按在源数据中出现的顺序附加地(即“在顶部”)绘制元素。 因此,如果我们按升序 LENGTH 排序,那么最长的道路应该最后打印。

library(dplyr)
ggplot() +
  geom_sf(data = st_as_sf(roads, "lines") %>% arrange(LENGTH), 
          aes(col = LENGTH, size = 3)) +
  scale_colour_gradient(low = "grey", high = "red") +
  coord_sf(xlim = c(557000, 560000), ylim = c(178000, 180000)) + 
  annotate(geom = "curve", x = 558000, y = 178500, xend = 558850, yend = 179150, curvature = -.3, arrow = arrow(length = unit(3, "mm")))

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM