在 Shiny 中绘制调整大小后获取轴范围

thi*_*ers 0 r shiny plotly r-plotly

我有一个带有时间序列数据 Plotly 图的 Shiny 应用程序。我希望用户能够平移 x(时间)轴,但保持一天的一致窗口。为此,我需要在每次调整大小后获取当前的 x 轴范围。

为什么我不只是使用rangeSlider? 因为我有大约 25,000 个数据点,并且使用 arangeSlider需要在应用程序初始化时将所有数据加载到图中,这会大大减慢速度。

Hal*_*wan 7

您可以event_data与plotly_relayout. 官方plotly文档有演示。

这是一个小例子,显示了一个情节时间序列的 xlimits。请注意,plotly_relayout将NULL在最初呈现绘图时返回,在用户调整页面大小时返回绘图尺寸,并在用户通过双击自动缩放绘图时返回 TRUE。

library(shiny)
library(plotly)

ui <- fluidPage(
    fluidRow(column(width = 6,
                    br(),
                    plotlyOutput("plot")),
             column(width = 6,
                    br(), br(),
                    htmlOutput("xlims"),
                    br(),
                    h4("Verbatim plotly `relayout` data"),
                    verbatimTextOutput("relayout")))
)

server <- function(input, output, session) {
    # create the plotly time series
  output$plot <- renderPlotly({
      today <- Sys.Date()
      tm <- seq(0, 600, by = 10)
      x <- today - tm
      y <- rnorm(length(x))
      p <- plot_ly(x = ~x, y = ~y, mode = 'lines', 
                   text = paste(tm, "days from today"), source = "source")
  })

  # print the xlims
  output$xlims <- renderText({
      zoom <- event_data("plotly_relayout", "source")
      # if plot just rendered, event_data is NULL
      # if user double clicks for autozoom, then zoom$xaxis.autorange is TRUE
      # if user resizes page, then zoom$width is pixels of plot width
      if(is.null(zoom) || names(zoom[1]) %in% c("xaxis.autorange", "width")) {
          xlim <- "default of plot"
      } else {
          xmin <- zoom$`xaxis.range[0]`
          xmax <- zoom$`xaxis.range[1]`
          xlim <- paste0("Min: ", xmin, "<br>Max: ", xmax)
      }
      paste0("<h4>X-Axis Limits:</h4> ", xlim)
  })

  # print the verbatim event_data for plotly_relayout
  output$relayout <- renderPrint({event_data("plotly_relayout", "source")})
}

shinyApp(ui, server)
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明