使用 ggplot 绘制 shapefile 和 gganimate 动画

89_*_*ple 6 r shapefile ggplot2 rgdal gganimate

样本数据

library(raster)
library(ggplot2)

my.shp <- getData('GADM', country = 'FRA', level = 1)
plot(my.shp)
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

如果我想使用 ggplot 绘制此数据:

my.shp_f <- fortify(my.shp, region = "ID_1")
ggplot(data = my.shp_f, aes(long, lat, group = group)) + geom_polygon(fill = "grey80")
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

问题一:为什么行政边界消失了?

问题 2: 我有另一个数据框,其中包含每个行政区划从第 1 天到第 365 天的 2 年日降雨量数据。

rain.data <- data.frame(ID_1 = rep(my.shp@data$ID_1, each = 2 * 365),
                        year = rep(rep(1981:1982, each = 365), times = 2),
                        day = rep(1:365, times = 4),
                        rain = sample(1:20, replace = T, 2 * 365 * 2))
Run Code Online (Sandbox Code Playgroud)

我想为这个形状文件创建一个从 1981 年第 1 天到 1982 年第 365 天的每日降雨动画。

我目前的总体方法是制作一个循环并将每天的降雨图保存为单独的.png文件,然后将这些文件堆叠为.gif. 但是,这导致我首先保存了 2 年 X 365 天的.png文件,然后将它们堆叠在一起。如果我有 30 年的数据,这将变得不可能。我读了这篇关于gganimate https://github.com/thomasp85/gganimate 的帖子,想知道是否有人可以演示如何使用 gganimate 使用上述数据生成动画地图

bos*_*hek 2

这个答案将事情引向了不同的方向,但我想尝试一下gganimate,这是一个很好的借口。我的修改主要是使用ggplot2 中的sf包和新的geom_sfGeom。我不喜欢这种老套的日期调整方式,所以这当然可以改进。我还只绘制了日期的一个子集 - 您拥有的数据量可能需要一些时间,具体取决于您的设置。无论如何,这就是我要做的:

library(raster)
library(ggplot2)
library(sf)
library(dplyr)
library(lubridate)
library(gganimate)
library(rmapshaper)

my.shp <- getData('GADM', country = 'FRA', level = 1)

## Convert the spatial file to sf
my.shp_sf <- st_as_sf(my.shp) %>% 
  ms_simplify()

## Here is how to plot without the rain data
ggplot(my.shp_sf) +
  geom_sf()

## Convert your data into a date
## this is very hacky and coule be improved
rain.data <- data.frame(ID_1 = rep(my.shp@data$ID_1, each = 2 * 365),
                        year = rep(rep(1981:1982, each = 365), times = 2),
                        day = rep(1:365, times = 4),
                        rain = sample(1:20, replace = T, 2 * 365 * 2)) 

date_wo_year <- as.Date(rain.data$day -1, origin = "1981-01-01")
rain.data$Date = ymd(paste0(rain.data$year, "-",month(date_wo_year),"-", day(date_wo_year)))

## Join the rain.data with a properly formatted date with the spatial data. 
joined_spatial <- my.shp_sf %>% 
  left_join(rain.data)

## Plot the spatial data and create an animation
joined_spatial %>% 
  filter(Date < as.Date("1981-02-28")) %>% 
  ggplot() +
  geom_sf(aes(fill = rain)) +
  scale_fill_viridis_c() +
  theme_void() +
  coord_sf(datum = NA) +
  labs(title = 'Date: {current_frame}') +
  transition_manual(Date) 
Run Code Online (Sandbox Code Playgroud)

  • @Crop89 使用最新版本的 gganimate 进行了修改和测试。冒着显而易见的风险,是否还为您安装了变压器? (4认同)