简体   繁体   English

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

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

I would like to know:我想知道:

a) what determines in which order elements are rendered in a ggplot2 plot? a)什么决定了元素在 ggplot2 图中的呈现顺序?

b) how can I influence this plot order of elements according to a variable or gradient colour scale? b)如何根据变量或渐变色标来影响元素的绘图顺序?

Context: I want to visualise a continuous variable of road network data (such as eg traffic flows).上下文:我想可视化道路网络数据的连续变量(例如交通流量)。 It is important that lines with high values are plotted last (so that they appear on top of lines with lower values) in order to make the plot legible.重要的是,高值线最后绘制(以便它们出现在低值线的顶部),以使图清晰易读。 At present, the default seems to plot lines in random order.目前,默认似乎以随机顺序绘制线条。

Below is an example using road length as a variable, the expected output would plot road lines in order of their value, ie, first grey lines, then red-grey lines, then darker red lines, and so forth.下面是一个使用道路长度作为变量的示例,预期输出将按其值的顺序绘制道路线,即首先是灰线,然后是红灰线,然后是较深的红线,依此类推。

Example data:示例数据:

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")

纽黑文道路数据

Here is a zoom in that illustrates quite well what the issue is: the grey road is covering the red road.这是一个放大图,可以很好地说明问题所在:灰色道路覆盖了红色道路。 However, what I would like to acchieve is that red road is plotted last (since it has a bigger length value).但是,我想要实现的是最后绘制红色道路(因为它具有更大的长度值)。

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")))

放大纽黑文道路数据

In general, ggplot plots the elements additively (ie "on top") in order of appearance in the source data.通常,ggplot 按在源数据中出现的顺序附加地(即“在顶部”)绘制元素。 So if we sort by ascending LENGTH, then the longest roads should print last.因此,如果我们按升序 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