首页 > 解决方案 > 将国家形状文件彼此相邻绘制以保持比例

问题描述

我想做的事

使用来自Natural Earth shapefile 数据集的国家级数据,我想将国家彼此相邻绘制,以展示它们的大小差异。例如,我想在刚果民主共和国旁边绘制喀麦隆和埃塞俄比亚,以让我的学生了解非洲国家大小的差异。

我试过的

使用 R,这是我尝试过的:

使用sf::st_read我已将 shapefile 导入为countries.

library(sf) # Easily work with spatial objects
library(tidyverse) # Brings in GGPlot
library(gridExtra) # Allows you to easily plot multiple GGPlots

gridExtra::grid.arrange(
ggplot(data = subset(countries, SOVEREIGNT %in% "Cameroon")) + geom_sf(),
ggplot(data = subset(countries, SOVEREIGNT %in% "Ethiopia")) + geom_sf(),
ggplot(data = subset(countries, SOVEREIGNT %in% "Democratic Republic of the Congo")) + geom_sf(),
ncol = 3)

结果

结果是三个比例不匹配的地图。尽管是最大的国家,但刚果民主共和国看起来比最小的国家喀麦隆还要小。

有什么优雅的方法可以进行这种比较吗?

标签: rggplot2plotgeospatialsf

解决方案


有几个选项。

A)提取国家然后使用仿射运算符将它们彼此相邻

Cameroon = subset(countries, SOVEREIGNT %in% "Cameroon")
Ethiopia = subset(countries, SOVEREIGNT %in% "Ethiopia")
DRC = subset(countries, SOVEREIGNT %in% "Democratic Republic of the Congo")
buffer = 1
Cameroon = st_geometry(Cameroon) - st_centroid(Cameroon)$geometry
DRC = st_geometry(DRC) - st_centroid(DRC)$geometry 
DRC = DRC - c(st_bbox(st_geometry(DRC))['xmin'],0)
DRC = DRC + c(st_bbox(st_geometry(Cameroon))['xmax'] + buffer,0)
Ethiopia = st_geometry(Ethiopia) - st_centroid(Ethiopia)$geometry
Ethiopia = Ethiopia - c(st_bbox(Ethiopia)['xmin'],0)
Ethiopia = Ethiopia + c(st_bbox(st_geometry(DRC))['xmax'] + buffer, 0)

ggplot(c(Cameroon, Ethiopia, DRC)) + geom_sf() + theme_minimal()

在此处输入图像描述

B) 使用方面

countries %>%
  subset(SOVEREIGNT %in% c("Cameroon", "Ethiopia", "Democratic Republic of the Congo")) %>%
  ggplot() + 
  geom_sf() +
  facet_grid(~SOVEREIGNT)

在此处输入图像描述

C)只需将它们绘制在正确的位置而不移动或分离它们:

countries %>%
  subset(SOVEREIGNT %in% c("Cameroon", "Ethiopia", "Democratic Republic of the Congo")) %>%
  ggplot() + 
  geom_sf()

在此处输入图像描述


推荐阅读