【发布时间】:2019-04-01 23:57:48
【问题描述】:
根据关于箱线图的this 问题和关于制作印度地图的my own question,在处理地图的各个层时,避免 ggplot 中代码重复的好方法是什么?
下面是一个 reprex 。我认为最简单的方法是: 1.保存带有州和国界的基本地图 2.添加区层(显示变量)。
想象为几十个变量重复第 2 步。
library(ggplot2)
library(sf)
library(raster)
# Download district and state data (should be less than 10 Mb in total)
distSF <- st_as_sf(getData("GADM",country="IND",level=2))
stateSF <- st_as_sf(getData("GADM",country="IND",level=1))
# Add country border
countryborder <- st_union(stateSF)
# STEP 1: Basic plot
basicIndia <- ggplot() +
geom_sf(data = stateSF, color = "white", fill = NA) +
geom_sf(data = countryborder, color = "blue", fill = NA) +
theme_dark()
# STEP 2: Adding the data layer underneath so it doesn't cover the other borders
indiaMap$layers <- c(geom_sf(data = distSF, fill = "red")[[1]], indiaMap$layers[[2:3]])
indiaMap$layers <- c(geom_sf(data = distSF, fill = "gold")[[1]], indiaMap$layers[[2:3]])
indiaMap
但是,这样一来,就无法对附加层进行哪怕是很小的修改,例如添加不同的标题。以下显然行不通,但说明了我的观点。
basicIndia$layers <- c(
geom_sf(data = distSF, aes(fill = GINI), color = "white", size = 0.2)[[1]] +
labs(title = "Gini coefficient"),
basicIndia$layers)
我是否以错误的方式解决问题?这是不能做的事情吗?
【问题讨论】: