以国家边界的形状裁剪地图
Cropping a map in the shape of a country boundary
我正在尝试下载温度数据并使用 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)")
但是,数据集包含整个世界的温度值。但我想形象化特定国家。我可以通过定义边界框来裁剪地图,但我想以国家/地区的形状(而不是正方形)裁剪地图。是否有任何包允许此功能?也许通过传递一个国家的 shapefile 并以该形状裁剪地图?
您可以将 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)")
我正在尝试下载温度数据并使用 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)")
但是,数据集包含整个世界的温度值。但我想形象化特定国家。我可以通过定义边界框来裁剪地图,但我想以国家/地区的形状(而不是正方形)裁剪地图。是否有任何包允许此功能?也许通过传递一个国家的 shapefile 并以该形状裁剪地图?
您可以将 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)")