首页 > 解决方案 > 在 R 中的地图上添加多边形,CRS 问题

问题描述

我正在尝试绘制瑞典地图,然后绘制我在其上创建的假形状。我有一个绘制瑞典自治市的脚本:

library(ggplot2)
library(sf)
library(smoothr)
library(jsonlite)


tmp <- tempfile()
download.file("http://api.thenmap.net/v2/se-7/geo/2020-06-06", destfile = tmp)

mun_name <- fromJSON("http://api.thenmap.net/v2/se-7/data/2020-06-06?language=en&data_props=name|shapeid|is_in") %>% 
  unnest(is_in) %>% 
  rename(county = is_in)

mun <- read_sf(tmp) %>% 
  left_join(mun_name, by = c("id" = "shapeid"))

ggplot(mun) +
  geom_sf(color="grey20",fill="grey95",size=.3) +
  theme_bw()

然后我有一个脚本,在其中制作多边形st_polygon

# make a polygon that is mostly inside sweden
sweden_polygon <-
  # create list of matrices and the first point same as last point
  list(
    matrix(
      c(14, 62, 
        12, 63, 
        14, 64, 
        16, 66, 
        20, 68,  
        20, 66,
        19, 65, 
        18, 63, 
        14, 62),
      ncol=2, byrow=T
    )
  ) 

# Create an sf polygon
sweden_polygon <-  sf::st_polygon(sweden_polygon)
# smooth the polygon
smooth_sweden_polygon <- smooth(sweden_polygon, method = "chaikin")

我可以用看似相同的坐标分别绘制它们,但是当我将它们绘制在一起时,它不起作用,因为多边形没有与瑞典匹配的 CRS。

# this works:
ggplot() +
  geom_sf(data=mun,color="grey20",fill="grey95",size=.3) +
  theme_bw()

# this works:
ggplot() +
  geom_sf(data=smooth_sweden_polygon) +
  theme_bw()

# this don't work:
ggplot() +
  geom_sf(data=mun,color="grey20",fill="grey95",size=.3) +
  geom_sf(data=smooth_sweden_polygon) +
  theme_bw()

我知道st_crs(mun)瑞典的坐标系是 WGS 84,但我不知道如何将其分配给我的多边形。

标签: rgisspatialsfggmap

解决方案


出于某种原因,我在安装时遇到了问题smoothr,所以这个答案与未平滑的多边形有关。

poly <- st_as_sfc(list(sweden_polygon), crs = 4326)

现在 poly 在同一个 CRS 中。然后,

ggplot(mun) +
  geom_sf(color="grey20",fill="grey95",size=.3) +
  theme_bw() +
  geom_sf(data = poly) 

给出:

在此处输入图像描述

这就是你所追求的吗?


推荐阅读