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

时间:2019-07-02 15:15:02

标签: javascript r shiny plotly r-plotly

我想在R中更改剧情动画的速度。但是,该动画不是由剧情动画提供的默认播放按钮触发的。根据JS代码,它是通过单击Shiny action按钮触发的。在这种情况下,似乎没有考虑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)

我想要一个用于绘制动画的帧和过渡持续时间的参数,并能够在代码中对其进行更改。

1 个答案:

答案 0 :(得分:2)

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

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)