将地图裁剪为国家边界的形状

问题描述 投票:0回答:2

我正在尝试下载温度数据并使用 R 对其进行可视化。我使用

raster
包下载温度并使用
ggplot2
对其进行可视化。

library(raster)
library(ggplot2)
library(magrittr)

tmax_data <- getData(name = "worldclim", var = "tmax", res = 10)
gain(tmax_data)=0.1
tmax_mean <- mean(tmax_data)
tmax_mean_df <- as.data.frame(tmax_mean, xy = TRUE, na.rm = TRUE)

tmax_mean_df %>%
  ggplot(aes(x=x,y=y)) +
  geom_raster(aes(fill = layer)) +
  labs(title = "Mean monthly maximum temperatures",
       subtitle = "For the years 1970-2000") +
  xlab("Longitude") +
  ylab("Latitude") +
  scale_fill_continuous(name = "Temperature (°C)")

但是,数据集包含全世界的温度值。但我想想象特定的国家。我可以通过定义边界框来裁剪地图,但我想以国家/地区的形状(而不是正方形)裁剪地图。有没有允许此功能的软件包?也许通过传递一个国家的形状文件并以该形状裁剪地图?

r raster spatial r-raster
2个回答
1
投票

您可以将

sf
包与
raster::crop
raster::mask
结合使用。这是法国的演示:

library(raster)
library(ggplot2)
library(magrittr)
library(sf)

tmax_data <- getData(name = "worldclim", var = "tmax", res = 10)
gain(tmax_data)=0.1
tmax_mean <- mean(tmax_data)

france_sf <- st_as_sf(maps::map(database = "france", plot = FALSE, fill = TRUE))

tmax_mean_france <- raster::crop(
  raster::mask(tmax_mean, as_Spatial(france_sf)),
  as_Spatial(france_sf)
)

tmax_mean_france_df <- as.data.frame(tmax_mean_france, xy = TRUE, na.rm = TRUE)

tmax_mean_france_df %>%
  ggplot(aes(x=x,y=y)) +
  geom_raster(aes(fill = layer)) +
  labs(title = "Mean monthly maximum temperatures **in France**",
       subtitle = "For the years 1970-2000") +
  xlab("Longitude") +
  ylab("Latitude") +
  scale_fill_continuous(name = "Temperature (°C)")


0
投票

将来自世界各地的辣椒绳索放在中东和非洲之间并连接欧洲它必须正确并连接各个国家

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