在现有的geom_sf图层下方插入geom_sf图层 [英] Insert geom_sf layer underneath existing geom_sf layers

查看:64
本文介绍了在现有的geom_sf图层下方插入geom_sf图层的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a basic map of India with states and borders, some labels, and a number of other specifications stored as a gg object. I'd like to generate a number of maps with a district layer, which will bear data from different variables.

为了防止地区地图覆盖州和国家/地区的边界,它必须位于所有先前的代码之前,我希望避免重复.

To prevent the district maps overwriting state and country borders, it must be before all the previous code, which I'd like to avoid repeating.

我认为我可以通过根据

I thought I could do this by calling on $layers for the gg object as per this answer. However, it throws an error. Reprex is below:

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

预期结果

任何帮助将不胜感激!

推荐答案

如果您查看 geom_sf(data = distSF),您会看到它是由两个元素组成的列表-您想要第一个包含图层信息的信息,因此 geom_sf(data = distSF,fill ="gold")[[1]] 应该起作用.

If you look at geom_sf(data=distSF) you'll see that it is a list made up of two elements - you want the first one which contains the layer information, so geom_sf(data = distSF, fill = "gold")[[1]] should work.

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

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

这篇关于在现有的geom_sf图层下方插入geom_sf图层的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆