r - 在现有 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
预期结果
任何帮助将非常感激!
解决方案
我仍然不确定我是否遗漏了您要查找的内容的详细信息,但ggplot2
会按照您提供的顺序绘制图层。所以像
ggplot(data) +
geom_col() +
geom_point(...) +
geom_line(...)
将绘制列,然后在这些之上点,然后在前一层之上的线。
地块也是如此sf
,这使得制作像这样的多个地理级别的地块变得容易。
(我rmapshaper::ms_simplify
在sf
对象上使用只是为了简化它们并加快绘图速度。)
library(dplyr)
library(ggplot2)
library(sf)
library(raster)
distSF <- st_as_sf(getData("GADM",country="IND",level=2)) %>% rmapshaper::ms_simplify()
...
然后,您可以按照需要显示的顺序添加图层来进行绘图。请记住,如果您需要对这些sf
s 中的任何一个进行其他计算,您可以提前或在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 日创建
推荐阅读
- rest - http GET中的ClientException“无效的响应原因短语”
- java - java中按位&运算符的时间复杂度是多少?
- python - 从 Beautiful Soup 中提取链接
- javascript - 如何将 .js 文件分解为不同的文件,如 PHP 的包含(或要求),这样我就不必使用命名空间
- ionic-framework - 每天开始特定日期的离子本地通知
- javascript - 如何让用户自定义通知条件?
- html - 如何创建 SVG 图标以及如何在 Web 应用程序上实现?
- r - 从r中的数据文件中的列中提取最频繁出现的元素
- node.js - 无法在版本 8 中运行 node js 项目
- python - 如何在python列表中的特定索引处插入元素