gganimate with changing scales (axis limits)
Asked Answered
R

2

9

I'd like to create a gif using gganimate, but my axis ranges vary wildly in one frame. This is causing all subsequent frames to be squeezed.

In ggplot2's facets, there's an option to have scales="free". Is there a way to have free scales in each frame of gganimate?

Here's an example:

library(gapminder)
library(ggplot2)
library(gganimate)
theme_set(theme_bw())

p <- ggplot(gapminder, aes(gdpPercap, lifeExp, size = pop, color = continent,
                           frame = year)) +
  geom_point() +
  scale_x_log10()

gganimate(p)

enter image description here

Now we move one of the data points to some extreme value. This squeezes the points in all subsequent unaffected frames.

gapminder[1, "lifeExp"] <- 1000
gapminder[1, "gdpPercap"] <- 1e60

p <- ggplot(gapminder, aes(gdpPercap, lifeExp, size = pop, color = continent, 
                           frame = year)) +
  geom_point() +
  scale_x_log10()

gganimate(p)  # smooshed

enter image description here

Reisman answered 7/12, 2016 at 19:45 Comment(5)
So you think it would be useful to have the scales calculated individually at every timestep? I don't see how that would be helpful.Lollop
I disagree. It would be useful for my application. Much like the facet_wrap() parameter scale="free" in ggplot2Reisman
But the animation would jump around every frame.Lollop
Only if the scale changed dramatically every frame. In my application only a single frame has a vastly different scale similar to the example here.Reisman
It's also useful for timeseries, for example here: youtube.com/watch?v=UatUDnFmNTYDhiman
N
10

You can try experimenting with view_follow().

1

Code

p <- ggplot(gapminder, aes(gdpPercap, lifeExp, size = pop, color = continent)) +
    geom_point() +
    labs(title = 'Year: {frame_time}', x = 'GDP per capita', y = 'life expectancy') +
    transition_time(year) +
    view_follow()

animate(p)
Notum answered 24/11, 2018 at 22:52 Comment(1)
I would suggest to replace view_follow() with view_zoom(). It produces nicer results for time series data.Chalcocite
C
2

To manually define the scales see view_step and view_step_manual (also view_zoom and view_zoom_manual).

Cushman answered 31/12, 2019 at 8:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.