首页 > 解决方案 > 如何将来自不同源/数据集的图(线/迹线)动态添加到 R(闪亮)中的绘图对象?

问题描述

我正在尝试将数据动态添加到 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

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

用户可能会继续此过程并以交互方式将更多数据集添加到绘图中。

干杯

标签: rshinyplotly

解决方案


这是一个关于如何使用extendTraces的示例,该示例plotlyProxy曾经在此处在线:

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)

推荐阅读