维护实时更新图表的缩放状态

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

问题:

当图表每次更新时如何保持绘图趋势字符缩放状态。我有示例示例来重现下面的问题。

示例:

library(shiny)
library(plotly)


generate_data <- function() {
  data.frame(
    timestamp = seq(as.POSIXct(Sys.time() - 3600), Sys.time(), by = "min"),
    value = runif(61, min = 100, max = 200) 
  )
}


ui <- fluidPage(
  plotlyOutput("trend_chart")
)


server <- function(input, output, session) {
  plot_ui_state <- reactiveValues(zoom = list())
  
  # Random data generation and plot update
  output$trend_chart <- renderPlotly({
    invalidateLater(10000, session) # Update every 10 seconds
    data <- generate_data()
    
    p <- plot_ly(data, x = ~timestamp, y = ~value, type = 'scatter', mode = 'lines') %>%
      layout(title = "Random Data Over Time")
    

  })

  

}

# Run the app
shinyApp(ui = ui, server = server)

r shiny plotly
1个回答
0
投票

如果我理解正确,您可以通过使用初始 x 轴范围值来维护您的绘图,该值将是缩放的偏移量。这将在您运行应用程序时创建。最大值将是

Sys.time()
值。您可以将这些传递给您的绘图的
layout
,如下所示:

library(shiny)
library(plotly)


generate_data <- function() {
  data.frame(
    timestamp = seq(as.POSIXct(Sys.time() - 3600), Sys.time(), by = "min"),
    value = runif(61, min = 100, max = 200) 
  )
}


ui <- fluidPage(
  plotlyOutput("trend_chart")
)


server <- function(input, output, session) {
  plot_ui_state <- reactiveValues(zoom = list())
  
  # Random data generation and plot update
  output$trend_chart <- renderPlotly({
    invalidateLater(10000, session) # Update every 10 seconds
    data <- generate_data()
    
    initial_range = data[1,1]
    
    p <- plot_ly(data, x = ~timestamp, y = ~value, type = 'scatter', mode = 'lines') %>%
      layout(title = "Random Data Over Time",
             xaxis = list(range = list(as.numeric(initial_range)*1000, as.numeric(Sys.time())*1000)),
             yaxis = list(range = list(100, 200)))
    
    
  })
  
  
  
}

# Run the app
shinyApp(ui = ui, server = server)

输出:

enter image description here

几分钟后,您将看到它更新轴:

enter image description here

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