Animated dot histogram, built observation by observation (using gganimate in R)

前端 未结 3 818
庸人自扰
庸人自扰 2021-02-12 14:37

I would like to sample points from a normal distribution, and then build up a dotplot one by one using the gganimate package until the final frame shows the full do

3条回答
  •  南方客
    南方客 (楼主)
    2021-02-12 15:08

    Try this. The basic idea is to the group the obs to frames, i.e. split by index and then accumulate the samples to frames, i.e. in frame 1 only the first obs is shown, in frame 2 obs 1 and 2, ..... Perhaps there is a more elegant way to achieve this, but it works:

    library(ggplot2)
    library(gganimate)
    library(dplyr)
    library(purrr)
    
    set.seed(42)
    
    # example data
    samples <- rnorm(100)
    index <- seq(1:length(samples))
    
    # Put data into a data frame
    df <- tibble(value=samples, index=index)
    
    # inflated df. Group obs together into frames
    df_ani <- df %>% 
      split(.$index) %>% 
      accumulate(~ bind_rows(.x, .y)) %>% 
      bind_rows(.id = "frame") %>% 
      mutate(frame = as.integer(frame))
    head(df_ani)
    #> # A tibble: 6 x 3
    #>   frame  value index
    #>      
    #> 1     1  1.37      1
    #> 2     2  1.37      1
    #> 3     2 -0.565     2
    #> 4     3  1.37      1
    #> 5     3 -0.565     2
    #> 6     3  0.363     3
    
    p_gg <- ggplot(data=df, mapping=aes(x=value))+
      geom_dotplot()
    p_gg
    #> `stat_bindot()` using `bins = 30`. Pick better value with `binwidth`.
    

    p_anim <- ggplot(data=df_ani, mapping=aes(x=value))+
      geom_dotplot()
    
    anim <- p_anim + 
      transition_manual(frame) +
      ease_aes("linear") +
      enter_fade() +
      exit_fade()
    anim
    #> `stat_bindot()` using `bins = 30`. Pick better value with `binwidth`.
    

    Created on 2020-04-27 by the reprex package (v0.3.0)

提交回复
热议问题