使用facet_grid绘制多个以公共多边形为重叠的空间多边形

问题描述 投票:1回答:1

我想从SpatialPolygonDataframe绘制空间数据。更具体地说,我想使用facet_grid()ggplot2在单个子图中绘制单个空间特征。另外,我想绘制一个公共的空间多边形作为每个面的叠加。

这里是使用美国及其单个州的空间数据集的示例。 (子集的)每个州都应显示在一个方面中,而美国的轮廓(在另一个空间数据集中提供)应绘制为每个方面中的覆盖图。以我目前的尝试,美国轮廓也被分割(基于ID)并分布在各个方面:

library(sf)
library(ggplot2)

usa <- as(st_as_sf(maps::map(database="usa",fill=T, plot =FALSE)),"Spatial")
usa_states <- as(st_as_sf(maps::map(database="state",fill=T, plot =FALSE)),"Spatial")
usa_states <- usa_states[c(1:5),]

ggplot(data=usa_states)+
  geom_polygon(data=usa, aes(x = long, y = lat,group=id), 
               size = 1, colour = "red",fill=NA)+
  geom_polygon(data=usa_states, aes(x = long, y = lat,group=id), 
               size = 0.3, fill = "green",color="black",alpha=0.2)+
  facet_grid(facets= id ~.)

我如何指定事实网格仅考虑usa_states数据集的'id',而不拆分美国轮廓?

enter image description here

ggplot2 sf facet-grid
1个回答
0
投票

这里是解决方案。无需将sf转换为sp。您可以使用geom_sf功能。问题是因为您的id值在两个数据集中都具有相同的名称。

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

usa <- st_as_sf(maps::map(database="usa",fill=T, plot =FALSE))
usa_states <- st_as_sf(maps::map(database="state",fill=T, plot =FALSE))
usa_states <- usa_states[c(1:5),]

usa_states <- usa_states %>% 
  rename(id = ID)

ggplot(data = usa_states)+
  geom_sf(size = 0.3, fill = "green",color="black",alpha=0.2)+
  geom_sf(data = usa ,
               size = 1, colour = "red",fill=NA) +
  facet_wrap(~ id)

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.