Search code examples
rggplot2gganimate

How to show the current value of y-axis in gganimate?


I have a dataframe df:

df = data.frame(name = "bird",
           value = seq(0, 1, length.out = 100),
           step = 1:100)

I want to animate this data by showing the variable value increasing. In the animation, I want to show the current step and value for that step.

This is what I have done so far:

library(ggplot2)

gg = ggplot(df, aes(name, value)) +
        geom_bar(stat = "identity", fill = "darkgreen") +
        coord_cartesian(ylim = c(0, 1))

gg + gganimate::transition_states(step) +
        ggtitle("Step: {closest_state}",
                subtitle = "Value: {frame}")

enter image description here

step is shown correctly, but clearly value is not.


Solution

  • In a similar vein, but without much piping and less computation (simple base R subsetting)

    library(gganimate)
    #> Loading required package: ggplot2
    df <- data.frame(
      name = "bird",
      value = seq(0, 1, length.out = 100),
      step = 1:100
    )
    
    anim <- ggplot(df, aes(name, value)) +
      geom_col(fill = "darkgreen") +
      coord_cartesian(ylim = 0:1) +
      transition_manual(frames = step) +
      ggtitle("Step: {current_frame}",
        subtitle = "Value: {round(df$value[as.integer(current_frame)], 2)}"
      )
    
    animate(anim, duration = 4)
    

    Created on 2022-06-29 by the reprex package (v2.0.1)

    PS I am using transition_manual with current_frame because gganimate did not show all frames. Another option would be to use set details = fps in animate