Search code examples
rggplot2ggplotly

How can I add annotation in ggplotly animation?


I am creating animated plotly graph for my assignment in r, where I am comparing several models with various number of observations. I would like to add annotation showing what is the RMSE of the current model - this means I would like to have text that changes together with slider. Is there any easy way how to do that?

Here is my dataset stored on GitHub. There already is created variable with RMSE: data

The base ggplot graphic is as follows:

library(tidyverse)
library(plotly)
p <- ggplot(values_predictions, aes(x = x))  +
    geom_line(aes(y = preds_BLR, frame = n, colour = "BLR")) +
    geom_line(aes(y = preds_RLS, frame = n, colour = "RLS")) + 
    geom_point(aes(x = x, y = target, frame = n, colour = "target"), alpha = 0.3) + 
    geom_line(aes(x = x, y = sin(2 * pi * x), colour = "sin(2*pi*x)"), alpha = 0.3)  +
    ggtitle("Comparison of performance) + 
    labs(y = "predictions and targets", colour = "colours")

This is converted to plotly, and I have added an animation to the Plotly graph:

plot <- ggplotly(p) %>%
        animation_opts(easing = "linear",redraw = FALSE)
plot

Thanks!


Solution

  • You can add annotations to a ggplot graph using the annotate function: http://ggplot2.tidyverse.org/reference/annotate.html

    df <- data.frame(x = rnorm(100, mean = 10), y = rnorm(100, mean = 10))
    
    # Build model
    fit <- lm(x ~ y, data = df)
    
    # function finds RMSE
    RMSE <- function(error) { sqrt(mean(error^2)) }
    
    library(ggplot2)
    ggplot(df, aes(x, y)) +
      geom_point() +
      annotate("text",  x = Inf, y  = Inf, hjust = 1.1, vjust = 2, 
               label = paste("RMSE", RMSE(fit$residuals)) )
    

    enter image description here

    There seems to be a bit of a problem converting between ggplot and plotly. However this workaround here shows a workaround which can be used:

    ggplotly(plot) %>%
      layout(annotations = list(x = 12, y = 13, text = paste("RMSE",
        RMSE(fit$residuals)), showarrow = F))
    

    enter image description here