【问题标题】:Cropping a map in the shape of a country boundary以国家边界的形式裁剪地图
【发布时间】:2021-05-11 04:37:28
【问题描述】:

我正在尝试下载温度数据并使用 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)")

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

【问题讨论】:

  • 看看 sf-package...它可以裁剪成一个盒子,也可以裁剪成任何其他加载的形状线..

标签: r raster spatial r-raster


【解决方案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)")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多