如何在 ggplotly 动画中添加注释?

joh*_*ken 1 r ggplot2 ggplotly

我正在为 r 中的作业创建动画绘图图,其中我将多个模型与不同数量的观察结果进行比较。我想添加注释,显示当前模型的 RMSE 是多少 - 这意味着我希望文本与滑块一起变化。有什么简单的方法可以做到这一点吗?

这是我存储在 GitHub 上的数据集。已经创建了 RMSE 变量:data

基本 ggplot 图形如下:

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")
Run Code Online (Sandbox Code Playgroud)

这被转换为绘图,并且我在绘图图中添加了一个动画:

plot <- ggplotly(p) %>%
        animation_opts(easing = "linear",redraw = FALSE)
plot
Run Code Online (Sandbox Code Playgroud)

谢谢!

Mic*_*per 5

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)) )
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

ggplot 和plotly 之间的转换似乎有点问题。但是,这里的解决方法显示了可以使用的解决方法:

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

在此输入图像描述