以国家边界的形式裁剪地图

时间:2021-02-07 10:41:56

标签: r raster spatial r-raster

我正在尝试下载温度数据并使用 R 对其进行可视化。我使用 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)") 对其进行可视化。

{{1}}

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

1 个答案:

答案 0 :(得分:1)

您可以将 sf 包与 raster::cropraster::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)")

enter image description here