我正在尝试下载温度数据,并使用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并将地图裁剪成该形状?
发布于 2021-02-09 00:22:15
您可以将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)")

https://stackoverflow.com/questions/66086949
复制相似问题