Search code examples
rggplot2gganimate

Not getting the desired title in gganimate - animated labels with expression


I want to add a unit of m^2 m^-2 (but as an expression) next to a variable using gganimate. For example the following gives me my desired output when I do it using only ggplot2:

library(ggplot2)
ggplot(mtcars, aes(wt, mpg)) + 
        geom_point() +
        labs(title = "Hp" ~ m^2 ~ m^-2)

However, when I do the following using gganimate I do not get a changing value of Hp, but {closest_state}

library(gganimate)
ggplot(mtcars, aes(wt, mpg)) + 
        geom_point() + 
        transition_states(hp) +
        labs(title = expression('Hp = {closest_state}' ~ m^2 ~ m^-2))

How could I solve this?


Solution

  • You could use ggtext::element_markdown() which allows a limited subset of Markdown format.
    This is enough for exponents and indices as in your example, but unfortunately Latex math isn't yet available.

    library(ggtext)
    library(gganimate)
    
    ggplot(mtcars, aes(wt, mpg)) + 
      geom_point() + 
      transition_states(hp) +
      labs(title = "Hp : {closest_state} m^2  m^-2")+
      theme(plot.title = element_markdown())
    

    enter image description here