将 gganimate 和 ggplot 用于箱线图:累积不起作用

Using gganimate and ggplot for a boxplot: Cumulative not working

我正在尝试为模拟模型制作动画,我想展示模拟运行时结果分布如何变化。

我见过 gganimate 用于散点图但不用于箱线图(或理想的小提琴图)。在这里,我提供了一个代表。

当我使用 sim_category(这是一定数量的模拟运行的桶)时,我希望结果是所有先前运行的累积,以显示总分布。

在这个例子中(和我的实际代码),cumulative = TRUE 不这样做。为什么是这样?

library(gganimate)
library(animation)
library(ggplot2)

df = as.data.frame(structure(list(ID = c(1,1,2,2,1,1,2,2,1,1,2,2),
                                  value = c(10,15,5,10,7,17,4,12,9,20,6,17),
                                  sim_category = c(1,1,1,1,2,2,2,2,3,3,3,3))))

df$ID <- factor(df$ID, levels = (unique(df$ID))) 
df$sim_category <- factor(df$sim_category, levels = (unique(df$sim_category))) 
ani.options(convert = shQuote('C:/Program Files/ImageMagick-7.0.5-Q16/magick.exe'))

p <- ggplot(df, aes(ID, value, frame= sim_category, cumulative = TRUE)) + geom_boxplot(position = "identity")

gganimate(p)

gganimate 的 cumulative 不会累积数据,它只是在后续帧出现时保留 gif 帧。为了实现你想要的,你必须在构建情节之前进行积累,大致如下:


library(tidyverse)
library(gganimate)

df <- data_frame(
  ID = factor(c(1,1,2,2,1,1,2,2,1,1,2,2), levels = 1:2),
  value = c(10,15,5,10,7,17,4,12,9,20,6,17),
  sim_category = factor(c(1,1,1,1,2,2,2,2,3,3,3,3), levels = 1:3)
) 

p <- df %>%
  pull(sim_category) %>% 
  levels() %>% 
  as.integer() %>%
  map_df(~ df %>% filter(sim_category %in% 1:.x) %>% mutate(sim_category = .x)) %>%
  ggplot(aes(ID, value, frame = factor(sim_category))) + 
  geom_boxplot(position = "identity")


gganimate(p)