[英]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.