如何在 R 中绘制流式直方图?

How to have streaming plotly histograms in R?

流图(又名实时图表)在 plotly 中非常容易使用,如本教程所示

https://plot.ly/r/streaming/#streaming-in-r

然而这篇文章只涉及散点图,我想知道流图是否可以用于直方图。

我改编了给定的示例,但无法使其正常工作。这是一个可重现的 Shiny 代码,只需将其复制到 app.R 文件中并在 Rstudio 中 运行 即可:

app.R

library(shiny)
library(plotly)

rand <- function() {
  runif(1, min=1, max=9)
}

ui <- fluidPage(

  headerPanel(h1("Streaming in Plotly", align = "center")),
  br(),
  div(actionButton("button", "Extend Trace"), align = "center"),
  br(),
  div(plotlyOutput("plot2"), id='graph')
)

server <- function(input, output, session) {

  p2 <- plot_ly(
    x = rnorm(n=1),
    type = 'histogram')%>%
    layout(
      xaxis = list(range = c(-10,10)),
      yaxis = list(range = c(0,10))
    )
  ##
  ## Output to UI
  output$plot2 <- renderPlotly(p2)
  ##
  ## Update once button clicked
  observeEvent(input$button, {
    data <- rnorm(n=1000)
    #while(TRUE){
    for( i in 1:1000 ){
      val <- data[i]
      Sys.sleep(0.1)
      plotlyProxy("plot2", session) %>%
        plotlyProxyInvoke("extendTraces", list(y=list(list(val))), list(0))
    }
  })
}

shinyApp(ui, server) 

您需要更改 plotlyProxyInvoke 中的 x 值而不是 y:

library(shiny)
library(plotly)

rand <- function() {
  runif(1, min=1, max=9)
}

ui <- fluidPage(

  headerPanel(h1("Streaming in Plotly", align = "center")),
  br(),
  div(actionButton("button", "Extend Trace"), align = "center"),
  br(),
  div(plotlyOutput("plot2"), id='graph')
)

server <- function(input, output, session) {

  p2 <- plot_ly(
    x = rnorm(n=1),
    type = 'histogram')%>%
    layout(
      xaxis = list(range = c(-10,10)),
      yaxis = list(range = c(0,10))
    )
  ##
  ## Output to UI
  output$plot2 <- renderPlotly(p2)
  ##
  ## Update once button clicked
  observeEvent(input$button, {
    data <- rnorm(n=1000)
    #while(TRUE){
    for( i in 1:1000 ){
      val <- data[i]
      Sys.sleep(0.1)
      plotlyProxy("plot2", session) %>%
        plotlyProxyInvoke("extendTraces", list(x=list(list(val))), list(0))
    }
  })
}

shinyApp(ui, server)