简体   繁体   中英

Sequentially Animate Changing Density Plots in R with gganimate

I am attempting to create an animation to show how the density for a normal distribution of data changes every time a new sample is added to a data set and the mean and standard deviation are updated. I have attempted to use the gganimate package and almost have what I'm looking for, but I cannot get the correct sequence in the animation. I'm fairly certain this is an obvious solution that's staring me right in the face so appreciate any help that can be provided.

A sample data frame can be recreated with the following code:

library(tidyverse)
library(gganimate)

sampled_data <- data.frame(Group = rep("A", 14),
                           week = c(0,2:5,7:14,20),
                           mean = c(30, 24.76111, 28.02916, 29.1741, 26.75879, 29.80132, 30.33864, 32.02787, 30.39993, 31.53138, 33.36167, 33.64898, 33.25587, 32.76954),
                           st_dev = c(10, 8.518451, 7.524797, 7.048826, 6.242289, 5.490741, 5.247176, 4.757057, 4.34478, 4.034823, 3.680196, 3.569206, 3.455505, 3.317643))

n = 20000

plot_df <- sampled_data %>% 
  uncount(n) %>% 
  mutate(value = rnorm(n(), mean, st_dev)) %>%
  select(Group, week, value)

This will give you a data frame that can be fed into ggplot for overlaying the densities with geom_density .

plot_df %>% 
  ggplot(aes(x=value, fill = as.factor(week))) +
  geom_density(alpha = 1)

在此处输入图片说明

The gganimate option that gets the closet to my intent is transition_reveal .

plot_df %>% 
  ggplot(aes(x=value, fill = as.factor(week))) +
  geom_density(alpha = 1) +
  transition_reveal(week)

在此处输入图片说明

The issue with the gif animation is that the weeks are not "revealed" in sequential order on top of each other. When I attempted to order the factor with seq_along() in the plot aesthetic, ggplot(aes(x=value, fill = seq_along(as.factor(week)))) , it removed the color fill from the plots and essentially turned the animation into a wireframe making the visualization useless for instruction purposes.

My ultimate goal is to have the weeks "reveled" on the plot in sequential order with the latest week on top of all previous weeks in the data set and retain the color fill. Thanks in advance for any help on this issue.

I think this is a bug in gganimate , since the plotting order appears to be correct (ie last week on top) before applying the transition.

However, an alternative method does work:

plot_df %>% 
  ggplot(aes(x=value, fill = as.factor(week))) +
  geom_density(alpha = 1) +
  transition_time(week) +
  shadow_mark()

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM