Search code examples
rggplot2gganimate

Positioning of violin plots when using gganimate


I am using ggplot2 3.0.0 and gganimate 0.1.1. Here is a MWE:

library(ggplot2)
library(gganimate)

df <- data.frame(year = rep(2000:2010, each = 50),
                 value = rnorm(550))

ggplot(df, aes(x = 0, y = value, frame = factor(year))) +
  geom_violin() -> p
gganimate(p)

This creates an animation where every frame looks like this

current output

Whereas I would like each frame to occupy the whole plot like this

desired output

How could I go about tweaking my code to get this result?

EDIT

This is what I would like to produce, this time using the actual data have. I made this by manually stitching together each frame of animation but this way is not sustainable for more complicated plots so I wish to use gganimate instead.


Solution

  • 1

    Just use transition_states() or transition_time().

    Code

    ggplot(df, aes(x = 0, y = value)) +
        geom_violin() +
        transition_states(year, transition_length = 3, state_length = 1) +
        labs(title = "{closest_state}")
    

    Data

    set.seed(1701)
    df <- data.frame(year = c(rep(2000:2010, each = 50)),
                     value = rnorm(550))