问题描述
我是sf
的新手。在以下代码中,我生成了两张地图,一张用于美国,一张用于澳大利亚。我想将这两个在同一ggplot
上彼此相邻移动。我试图在longitude
内更改澳大利亚的latitude
和geometry
值。我只是想知道是否有一种快速的方法来做到这一点。任何建议将不胜感激。
library(tidyverse)
library(sf)
library(rnaturalearth)
map_au <-ne_states(country = c("australia"),returnclass ="sf") %>%
select(state = name,geometry)
map_us <-ne_states(country = c("united states of america"),geometry) %>%
filter(!state %in% c("Alaska","Hawaii"))
ggplot(data = map_us,aes(fill = state))+
geom_sf()+
geom_sf(data = map_au)+
theme(legend.position = "none")
由reprex package(v0.3.0)于2020-11-04创建
解决方法
sf
允许您对几何图形执行arbitrary affine transformations,包括翻译。我们可以通过仅添加坐标矢量或使用变换矩阵(此处不必要)来移动几何。我们还需要替换对象的CRS以便再次绘制它。
请注意,这实际上是在平面上移动形状,而这可能并非您想要的。特别是,没有保留真实的区域和距离(我不知道澳大利亚从北到南的纬度是否比美国大陆的纬度还要大……)
library(tidyverse)
library(sf)
#> Linking to GEOS 3.8.1,GDAL 3.1.1,PROJ 6.3.1
library(rnaturalearth)
map_au <- ne_states(country = c("australia"),returnclass = "sf") %>%
select(state = name,geometry)
map_us <- ne_states(country = c("united states of america"),geometry) %>%
filter(!state %in% c("Alaska","Hawaii"))
map_au_moved <- map_au
st_geometry(map_au_moved) <- st_geometry(map_au_moved) + c(-180,60)
st_crs(map_au_moved) <- st_crs(map_au)
ggplot(data = map_us,aes(fill = state))+
geom_sf()+
geom_sf(data = map_au_moved)+
theme(legend.position = "none")
由reprex package(v0.3.0)于2020-11-03创建