javascript - 如何在 R 中的 javascript 代码中更改动画速度?

标签 javascript r shiny plotly r-plotly

我想在 R 中更改 plotly 动画的速度。但是,该动画不是由 plotly 动画提供的默认播放按钮触发的。根据 JS 代码,它通过单击 Shiny 操作按钮触发。在这种情况下,似乎没有考虑 animation_opts() 参数。

我已经尝试更改 animation_opts() 参数,例如“frame”和“transition”,但动画保持不变。我还尝试在 javascript 代码中更改这些参数,但动画甚至没有开始。

library(shiny)
  library(plotly)
  library(htmlwidgets)

  ui <- fluidPage(
    actionButton("anim", "Animate"),
    plotlyOutput("plot")
  )

  server <- function(input, output){
    output[["plot"]] <- renderPlotly({
      df <- data.frame(
        x = c(1,2,1), 
        y = c(1,2,1), 
        f = c(1,2,3)
      )
      df %>%
        plot_ly(
          x = ~x,
          y = ~y,
          frame = ~f,
          type = 'scatter',
          mode = 'markers',
          marker = list(size = 20),
          showlegend = FALSE
        ) %>% 
        animation_opts(frame = 5000, transition = 4500, redraw = FALSE) %>%
        animation_button(visible = FALSE) %>%
        onRender("
          function(el,x){
            $('#anim').on('click', function(){Plotly.animate(el);});
          }")

    })
  }

  shinyApp(ui, server)

我想为 plotly 动画的帧和过渡持续时间设置一个参数,并能够在代码中更改它。

最佳答案

以下是设置这些选项的方法:

library(shiny)
library(plotly)
library(htmlwidgets)

ui <- fluidPage(
  actionButton("anim", "Animate"),
  plotlyOutput("plot")
)

server <- function(input, output){
  output[["plot"]] <- renderPlotly({
    df <- data.frame(
      x = c(1,2,1), 
      y = c(1,2,1), 
      f = c(1,2,3)
    )
    df %>%
      plot_ly(
        x = ~x,
        y = ~y,
        frame = ~f,
        type = 'scatter',
        mode = 'markers',
        marker = list(size = 20),
        showlegend = FALSE
      ) %>% 
#      animation_opts(frame = 5000, transition = 4500, redraw = FALSE) %>%
      animation_button(visible = FALSE) %>%
      onRender("
          function(el,x){
            $('#anim').on('click', function(){
              Plotly.animate(el, 
                null,
                {
                  transition: {
                    duration: 2000,
                    easing: 'cubic-in-out'
                  },
                  frame: {
                    duration: 2000
                  }
                }
              );
            });
          }")
  })
}

shinyApp(ui, server)

关于javascript - 如何在 R 中的 javascript 代码中更改动画速度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56855505/

相关文章:

r - 如何在不重新加载所有内容的情况下突出显示带有 Shiny 刻面的ggplot上的点?

javascript - 连接对象属性值

javascript - Firebase 警告 : Using an unspecified index when search data with Firebase Cloud Function

R - 向量中特定值的嵌套循环

r - 提取交互式图中鼠标单击的确切坐标

r - 有没有办法在plotly_click之后渲染更详细的表格?

javascript - Javascript 代码中的重复元素

javascript - 获取 Canvas 内的鼠标位置

r - 源自同一个 hclust 对象的图之间的颜色变化,需要统一用户体验

r - ggplot2:stat_summary 与 geom_boxplot 的水平位置