I'm not an expert at either geospatial data or gganimate, but I managed to get something that resembles an answer to your question by doing the following.
(我既不是地理空间数据专家也不是地理专家,但我通过执行以下操作设法获得了类似于您问题的答案的东西。)
We'll start out in a similar fashion to how you started your example, but we also load the gganimate package. (我们将以与您开始示例类似的方式开始,但是我们还将加载gganimate程序包。)
library(tidyverse)
library(rnaturalearth)
library(rnaturalearthdata)
library(gganimate) # also needs transformr
## Do all previous stuff
set.seed(1234)
ww <- ne_countries(scale = "medium", returnclass = "sf")
ll <- ww$name %>% length
val <- sample(c("a","b","c","d"), ll, replace=T)
bb <- ne_download(type = "wgs84_bounding_box", category = "physical",
returnclass = "sf")
ww <- ww %>% mutate(value=val)
Then, for each of our timepoints, we copy the data and assign a group per shape, timepoint and new fill variable.
(然后,对于每个时间点,我们复制数据并为每个形状,时间点和新的填充变量分配一个组。)
The grouping is need because by default, the fill will determine the grouping and the animations will show countries all jumping across the map. (需要分组是因为默认情况下,填充将确定分组,并且动画将显示在地图上跳跃的国家/地区。)
newdf <- lapply(seq_len(5), function(i) {
new <- ww
new$group <- seq_len(nrow(new))
new$value <- sample(letters[1:4], nrow(new), replace = TRUE)
new$time <- i
new
})
newdf <- do.call(rbind, newdf)
Then we make a plot.
(然后我们作图。)
The main difference is that I assign a group in the geom_sf()
and add transition_time(time)
. (主要区别在于我在geom_sf()
分配了一个组,并添加了transition_time(time)
。)
Also, I add a subtitle to keep track of the animation state. (另外,我添加了一个字幕来跟踪动画状态。)
gpl1 <- ggplot(data = newdf) +
geom_sf(aes(fill=value, group = group), col = "black", lwd = 0.3 )+
xlab(NULL) + ylab(NULL) +
ggtitle("World Export of Merchandise", subtitle = "{frame_time}")+
geom_sf(data = bb, col = "grey", fill = "transparent") +
theme(plot.background = element_rect(fill = "white"),
panel.background = element_rect(fill = 'white'),
panel.grid.major = element_line(colour = "grey"),
legend.position="top",
plot.title = element_text(lineheight=.8, size=24, face="bold",
vjust=1),
legend.text = element_text(vjust=.4,lineheight=1,size = 14),
legend.title = element_text(vjust=1,lineheight=1, size=14,
face="bold" )) +
transition_time(time)
# coord_sf(crs = "+proj=eqearth +wktext") # couldn't get this coord to work
And then we animate:
(然后我们制作动画:)
ani <- animate(gpl1)