繁体   English   中英

如何将来自不同来源/数据集的绘图(线/迹线)动态添加到 R (Shiny) 中的绘图对象?

[英]How to dynamically add plots (lines/traces) from different sources/datasets to a plotly object in R (Shiny)?

我正在尝试将数据动态添加到 plotly 对象。 新数据来自可能具有不同长度的不同数据集。 假设有以下数据:

假设 df1 是:

date|value
1/1/2020|1
2/1/2020|23
...
10/1/2020|40

我可以轻松地将其绘制为:

plot_ly (df1, x = ~date, y = ~value, mode = 'lines', type = 'scatter', name = 'trace 0')

但是,我有一个选择框,用户可以以交互方式选择具有相同列名但长度不同的任何其他数据集,假设用户选择 df2:

date|value
1/1/2019|1
2/1/201|24
... 
10/1/2020|43

考虑到列名相同但长度不同,如何将新选择的数据集添加到上一个图中?

用户可以继续这个过程并以交互方式向图中添加更多数据集。

干杯

下面是一个关于如何使用extendTracesplotlyProxy ,它曾经在这里在线:

library(shiny)
library(plotly)

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

ui <- fluidPage(      
  headerPanel(h1("Streaming in Plotly: Multiple Traces", align = "center")),
  br(),
  div(actionButton("button", "Extend Traces"), align = "center"),
  br(),
  div(plotlyOutput("plot"), id='graph')
)

server <- function(input, output, session) {
  
  p <- plot_ly(
    type = 'scatter',
    mode = 'lines'
  ) %>%
    add_trace(
      y = c(rand(),rand(),rand()),
      line = list(
        color = '#25FEFD',
        width = 3
      )
    ) %>%
    add_trace(
      y = c(rand(),rand(),rand()),
      line = list(
        color = '#636EFA',
        width = 3
      )
    ) %>%
    layout(
      yaxis = list(range = c(0,10))
    )
  
  output$plot <- renderPlotly(p)
  
  observeEvent(input$button, {
    while(TRUE){
      Sys.sleep(1)
      plotlyProxy("plot", session) %>%
        plotlyProxyInvoke("extendTraces", list(y=list(list(rand()), list(rand()))), list(1,2))
    }
  })
  
}

shinyApp(ui, server)

感谢@ismirsehregal 的提示,我以这种方式修复了代码:

第 1 步:我用空布局初始化了绘图:

output$my_plot <- renderPlotly ({
       plot_ly (mode = 'lines') %>%
            layout(showlegend = TRUE) 
    })

第 2 步:我创建了一个按钮,供用户使用“plotlyProxy”和“plotlyProxyInvoke”函数从新选定的数据集添加跟踪:

observeEvent (input$add_trace, {

        plotlyProxy("my_plot", session) %>%
          plotlyProxyInvoke("addTraces", list (x = selected_dataset$date, y = selected_dataset$close,  mode = 'lines', type = 'scatter') 
        
        })

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM