使用gganimate和ggplot作为箱图:累积不起作用

时间:2017-06-04 14:13:26

标签: r ggplot2 gganimate

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

我已经看到用于散点图的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)

1 个答案:

答案 0 :(得分: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)

enter image description here

相关问题