John Hall
John Hall

Reputation: 23

Creating a smooth transition between two time series bar charts with gganimate

I am attempting to make an animation with gganimate that starts with the past 10 years of crime data. Once the animation starts, I would like to add historical years going back to 1970 (when crime was much higher). This would appear as a "zoom out" with free axes. So far, I can start with 2018 and add years sequentially backwards like this:

# Create dataset
dat <- tibble(year = 1970:2018)
dat$crime <- 100 * exp(-0.02*(dat$year-1970))


p <- ggplot(dat, aes(x=year, y = crime)) +
  geom_bar(stat = "identity") +
  transition_states(-year, transition_length = 4, state_length = 2) +
  view_follow() + shadow_mark()

animate(p)

CrimeAnimation

I am having difficulty starting with a 10 year historical plot (instead of just one year), prior to zooming out to the past 30-40 years. Any help would be appreciated!

Upvotes: 2

Views: 712

Answers (1)

Roman
Roman

Reputation: 4989

Use a custom state variable to group the desired years.

1

Data

dat <- tibble(year = 1970:2018)
dat$crime <- 100 * exp(-0.02*(dat$year-1970))

# state variable called "time" for grouping
dat$time <- c(40:2, rep(1, 10))

Code

p <- ggplot(dat) +
    geom_col(
        aes(
            x = year, 
            y = crime
        )
    ) +
    # states depend on "time", not "year"
    transition_states(
        time, 
        transition_length = 4, 
        state_length = 2
    ) +
    view_follow() + 
    shadow_mark()

animate(p)

PS: That was a really concise, well-formatted, and reproducible first question! Keep it up!

Upvotes: 1

Related Questions