首页 > 解决方案 > 在现有 geom_sf 图层下方插入 geom_sf 图层

问题描述

我有一张印度的基本地图,其中包含州和边界、一些标签以及许多其他规范,这些规范存储为 gg 对象。我想生成一些带有区域图层的地图,这些地图将包含来自不同变量的数据。

为了防止地区地图覆盖州和国家边界,它必须在所有以前的代码之前,我想避免重复。

我想我可以通过$layers按照这个答案调用 gg 对象来做到这一点。但是,它会引发错误。代表如下:

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 border

countryborder <- st_union(stateSF)

# Basic plot

basicIndia <- ggplot() +
  geom_sf(data = stateSF, color = "white", fill = NA) +
  geom_sf(data = countryborder, color = "blue", fill = NA) +
  theme_dark()

basicIndia

# Data-bearing plot

districts <- ggplot() +
  geom_sf(data = distSF, fill = "gold")

basicIndia$layers <- c(geom_sf(data = distSF, fill = "gold"), basicIndia$layers)

basicIndia
#> Error in y$layer_data(plot$data): attempt to apply non-function

预期结果

任何帮助将非常感激!

标签: rggplot2sf

解决方案


我仍然不确定我是否遗漏了您要查找的内容的详细信息,但ggplot2会按照您提供的顺序绘制图层。所以像

ggplot(data) +
  geom_col() +
  geom_point(...) +
  geom_line(...)

将绘制列,然后在这些之上点,然后在前一层之上的线。

地块也是如此sf,这使得制作像这样的多个地理级别的地块变得容易。

(我rmapshaper::ms_simplifysf对象上使用只是为了简化它们并加快绘图速度。)

library(dplyr)
library(ggplot2)
library(sf)
library(raster)

distSF <- st_as_sf(getData("GADM",country="IND",level=2)) %>% rmapshaper::ms_simplify()
...

然后,您可以按照需要显示的顺序添加图层来进行绘图。请记住,如果您需要对这些sfs 中的任何一个进行其他计算,您可以提前或在geom_sf.

ggplot() +
  geom_sf(data = distSF, fill = "gold", size = 0.1) +
  geom_sf(data = stateSF, color = "white", fill = NA) +
  geom_sf(data = countryborder, color = "blue", fill = NA)

关于尝试将一个绘图添加到另一个绘图:ggplot2分层工作,因此您创建一个基础ggplot对象,然后在其上添加几何图形。例如,您可以制作两个有效的图:

state_plot <- ggplot(stateSF) + 
  geom_sf(color = "white", fill = NA)
country_plot <- ggplot(countryborder) + 
  geom_sf(color = "blue", fill = NA)

但是您不能添加它们,因为您将有 2 个基础ggplot对象。这应该是你提到的错误:

state_plot + 
  country_plot
#> Error: Don't know how to add country_plot to a plot

相反,如果您需要制作绘图,则在其上添加其他内容,制作 base ggplot,然后添加几何图层,例如geom_sf具有不同数据集的 a。

state_plot +
  geom_sf(data = countryborder, fill = NA, color = "blue")

reprex 包(v0.2.1)于 2018 年 10 月 29 日创建


推荐阅读