colonus
colonus

Reputation: 329

add geoms with gganimate

I want to create an animated ggplot with gganimate. Is there a way to add several animated geoms with gganimate? So as in the example below using transition_states() I would want the geom_smooth() to appear as a new state and not with the geom_points(). In the end I would want to control the duration, enter and exit of the second geom seperately.

  library(gganmiate)
  ggplot(iris, aes(x = Petal.Width, y = Petal.Length)) +
  geom_smooth(aes(colour = Species), method = "lm", se = F) +
  geom_point() +
  transition_states(Species,
                    transition_length = 2,
                    state_length = 1)

enter image description here

Upvotes: 0

Views: 240

Answers (1)

Steffen Moritz
Steffen Moritz

Reputation: 7730

In general, controlling individual components separately is possible with gganimate. However, I don't think what you want to do works currently (but maybe someone knows better - would be highly appreciated).

Use transition_components() instead of transition_states()

From the documentation:

transition_components(): This transition allows individual visual components to define their own "life-cycle". This means that the final animation will not have any common "state" and "transition" phase as any component can be moving or static at any point in time.

Here is an example controlling two points separately at each time step:

data <- data.frame(
      x = c(1,1,1,1,1,2,2,2,2,2),
       y = c(1,2,3,4,5,1,2,3,4,5),
       time = c(1, 2, 3, 4, 5, 1, 2, 3, 4, 5),
       id = c(1,1,1,1,1,2,2,2,2,2),
      col = c("red","red","red","red","red","red","blue","yellow","green","pink")
   )

 anim2 <- ggplot(data, aes(x, y, group = id, size = 10, colour = col)) +
       geom_point() + transition_components(time)
 
 anim2

enter image description here

Here you could exactly define what happens to each point at each time step. Or even define at which time steps it should appear.

Looks promising for your problem, however this function (currently) does not work with lines.

When you try to integrate these somehow in this workflow you get the following error:

Error: path layers not currently supported by transition_components

So basically everything with a line geom_line, geom_smooth,... is not useable with this function.

I think what you want is to prevent the strange behavior of the points making the transition and the geom_smooth lagging behind. Maybe you could just set in your code transition_length = 0 to prevent this.

Upvotes: 1

Related Questions