【发布时间】:2018-03-14 02:33:46
【问题描述】:
我有一个闪亮的应用程序,其中包含时间序列数据的 Plotly 图。我希望用户能够平移 x(时间)轴,但保持一天的一致窗口。为此,我需要在每次调整大小后获取当前的 x 轴范围。
为什么我不只是使用rangeSlider?因为我有大约 25,000 个数据点,并且使用 rangeSlider 需要在应用程序初始化时将所有数据加载到绘图中,这会大大减慢速度。
【问题讨论】:
我有一个闪亮的应用程序,其中包含时间序列数据的 Plotly 图。我希望用户能够平移 x(时间)轴,但保持一天的一致窗口。为此,我需要在每次调整大小后获取当前的 x 轴范围。
为什么我不只是使用rangeSlider?因为我有大约 25,000 个数据点,并且使用 rangeSlider 需要在应用程序初始化时将所有数据加载到绘图中,这会大大减慢速度。
【问题讨论】:
您可以将event_data 与plotly_relayout 一起使用。官方的plotly 文档有一个demonstration。
这是一个小例子,显示了一个情节时间序列的 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)
【讨论】: