【发布时间】:2019-07-26 05:25:07
【问题描述】:
我的县级数据记录了 2002 年至 2018 年间在该县首次检测到入侵性害虫的年份。我使用 ggplot2 和地图包创建了一张地图,该地图包根据害虫的年份用颜色填充县多边形被检测到。
**有没有办法使用 gganimate 包为这个地图制作动画,第一帧只填充检测日期为 2002 年的多边形,第二帧填充检测日期为 2003 年或更早的多边形(所以 2002 年和2003),用于检测日期为 2004 年或更早(2002、2003、2004)等的第三帧? ** 说明:我希望所有县多边形始终可见并最初填充为白色,并且动画的每一帧都会根据检测年份添加县的填充。
我尝试将transition_reveal(data$detect_year) 与静态图一起使用,但收到错误消息“沿数据必须是整数、数字、POSIXct、日期、difftime 或欧姆”。
以下是可重现示例的一些代码:
library(dplyr)
library(purrr)
library(maps)
library(ggplot2)
library(gganimate)
# Reproducible example
set.seed(42)
map_df <- map_data("county") %>%
filter(region == "minnesota")
map_df$detection_year <- NA
# Add random detection year to each county
years <- 2002:2006
map_list <- split(map_df, f = map_df$subregion)
map_list <- map(map_list, function(.x) {
.x$detection_years <- mutate(.x, detection_years = sample(years, 1))
})
# collapse list back to data frame
map_df <- bind_rows(map_list)
map_df$detection_years <- as.factor(map_df$detection_years)
# Make plot
static_plot <- ggplot(map_df,
aes(x = long,
y = lat,
group = group)) +
geom_polygon(data = map_df, color = "black", aes(fill = detection_years)) +
scale_fill_manual(values = terrain.colors(n = length(unique(map_df$detection_years))),
name = "Year EAB First Detected") +
theme_void() +
coord_fixed(1.3)
animate_plot <- static_plot +
transition_reveal(detection_years)
如果可以使用 gganimate 做到这一点,我愿意,但如果有人有想法,我也愿意接受其他解决方案。
【问题讨论】: