1

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

我见过 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)
4

1 回答 1

1

gganimate的累积不会累积数据,它只是将 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)

在此处输入图像描述

于 2017-06-04T18:38:46.200 回答