添加文本时交互式图形闪烁

问题描述 投票:0回答:1

我正在尝试制作一个交互式绘图图(对 R 使用 plotly),其中每一帧都是一个直方图。在每一帧的顶部,我想写一些文字。以下最小示例说明了我想要实现的目标。

library(dplyr)
library(plotly)

dat <- tibble(x = rnorm(10000,0,1), f = rep(1:10, each = 1000))
dat2 <- tibble(x = -3, y = 70, f = seq(1,10), txt = paste0("frame ", seq(1,10)))

plot_ly() %>%
  add_trace(data = dat,
            x = ~x,
            frame = ~f,
            type = "histogram",
            showlegend = FALSE) %>%
  add_trace(data = dat2,
            x = ~x,
            y = ~y,
            frame = ~f,
            type = "scatter",
            mode = "text",
            text = ~txt,
            showlegend = FALSE) %>%
  animation_opts(
    transition = 0,
    frame = 100,
  ) %>%
  config(staticPlot = TRUE)

这里的问题是,当我在每一帧的顶部添加文本时,动画开始闪烁。如果我删除第二个

add_trace
,就不会有闪烁。知道为什么会发生这种情况以及如何解决它吗?

r plotly
1个回答
0
投票

你应该使用

add_annotations
而不是
add_trace
。您可以稍微调整 @kat here 编写的代码,以确保文本在情节的每一帧中顺利显示。在这种情况下,您必须确保每个帧的迭代都采用注释数据帧的输入。这是一些可重现的代码:

library(dplyr)
library(plotly)

dat <- tibble(x = rnorm(10000,0,1), f = rep(1:10, each = 1000))
dat2 <- tibble(x = -3, y = 70, f = seq(1,10), txt = paste0("frame ", seq(1,10)))

p1 <- plot_ly() %>%
  add_trace(data = dat,
            x = ~x,
            frame = ~f,
            type = "histogram",
            showlegend = FALSE) %>%
  animation_opts(
    transition = 0,
    frame = 100
  ) %>%
  config(staticPlot = TRUE)

p2 <- plotly_build(p1)

lapply(1:nrow(dat2), 
       function(i){
         annotation = list(
           type = "text",
           x = dat2[i,]$x,
           y = dat2[i,]$y,
           xref = "x",
           yref = "y",
           showarrow = F,
           text = dat2[i, ]$txt) 
         p2$x$frames[[i]]$layout <<- list(annotations = list(annotation)) 
       })

p2

创建于 2023-03-28 与 reprex v2.0.2

© www.soinside.com 2019 - 2024. All rights reserved.