修复动画 ggplot 中突然的 changes/transitions

Fixing abrupt changes/transitions in animated ggplot

我想制作一个动画 ggplot,显示一年中各个国家/地区的每日价值。多亏了一些有用的 questions/answers .

我才能够做到这一点

虽然下面的代码成功制作了一张 gif,但 changes/transitions 国家向上移动或 down/overtake 彼此非常突然(即瞬时)。它不像链接 post.

中的示例那样流畅

我不完全确定为什么会这样,非常感谢您的帮助。提前感谢任何能够提供一些见解的人。代码如下。

library(tidyverse)
library(ggplot2)
library(gganimate)
library(gifski)
library(png)

# Generate some fake data 
n=365  
df <- data.frame(country_name = rep(c("Country_1","Country_2","Country_3","Country_4","Country_5"), n, replace=FALSE),
                 date = rep(seq.Date(as.Date("2021-01-01"), as.Date("2021-12-31"), "day"),each=5), # each is number of countries 
                 incidents=sample(1:100, size = 25, replace=TRUE
                 ))

# Make cumulative number of events
df = df %>% 
  group_by(country_name) %>%
  arrange(date) %>%
  mutate(cumulative_incidents = cumsum(incidents)) %>%
  ungroup()

# create integer rankings (I thought the *1 would make things smoother)
df = df %>% 
  group_by(date) %>%
  mutate(rank = min_rank(-cumulative_incidents *1), 
         Value_rel = cumulative_incidents/cumulative_incidents[rank==1],
         Value_lbl = paste0(" ",round(cumulative_incidents/1e9))) %>%
  ungroup()
 
# make the static plot
my_plot = ggplot(df, aes(-rank,Value_rel, fill = country_name)) +
  geom_col(width = 0.8, position="identity") +
  coord_flip() + 
  geom_text(aes(-rank,y=0,label = country_name,hjust=0)) +       
  geom_text(aes(-rank,y=Value_rel,label = cumulative_incidents, hjust=0)) + 
  theme_minimal() +
  theme(legend.position = "none",axis.title = element_blank()) +
  # animate along Year
  transition_states(date,4,1)

# animate the plot
animate(my_plot, 100, fps = 25, duration = 20, width = 800, height = 600)

你的数据时间分辨率非常高,你有365个时间点,但你的动画只有500帧。因此,这些平滑切换发生在 500 / 365 = ~1.4 帧内并且不可见。

要么让你的动画更长,降低数据的时间分辨率,要么在转换中手动编码。例如,如果我们每月只提供一次数据,会发生以下情况:

df2 <- filter(df, date %in% seq(min(date), max(date), 'week'))
my_plot <- ggplot(df2, aes(-rank,Value_rel, fill = country_name)) +
  geom_col(width = 0.8, position="identity") +
  coord_flip() + 
  geom_text(aes(-rank,y=0,label = country_name,hjust=0)) +       
  geom_text(aes(-rank,y=Value_rel,label = cumulative_incidents, hjust=0)) + 
  theme_minimal() +
  theme(legend.position = "none",axis.title = element_blank()) +
  # animate along Year
  transition_states(date, transition_length = 10, state_length = 1)
animate(my_plot, fps = 25, duration = 20, width = 800, height = 600)