在闪亮的图中添加动态数量的轨迹

发布于 2025-01-19 08:27:16 字数 218 浏览 4 评论 0原文

有人要求将动态数量的跟踪数添加到plot_ly绘图中。这是基于最近的问题已被删除。我希望下面的答案可以帮助其他正在寻找类似情况的答案的人。

Someone requested to add dynamic number of traces to a plot_ly plot. This is based on a recent question that has been deleted. I hope the answer below helps someone else who is looking for an answer with a similar situation.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

沫尐诺 2025-01-26 08:27:16

如上所述,这是我早期答案在这里的重复。

但是, @ybs的方法过于复杂,我想提供直接比较的可能性。使用data.frameggplotplotly是首选的方法(使用eg data.table ::融化从宽到长)。这样,我们可以使用plot_ly's splitnamecolor参数参数以基于数据创建多个跟踪:

library(shiny)
library(shinydashboard)
library(plotly)
library(gapminder)

DF <- gapminder[, c(1, 3, 4)]

ui <- dashboardPage(
  dashboardHeader(),
  dashboardSidebar(
    selectizeInput(
      "col",
      "Pick a column for y-axis to plot, if ticked in checkbox below",
      choices = NULL,
      selected = NULL,
      multiple = TRUE
    ),
    checkboxGroupInput("chk", "Display Plot", choices = DF$country[1])
  ),
  dashboardBody(tabsetPanel(id = "tabs",
                            tabPanel(
                              "Plot data" , plotlyOutput("tseries")
                            )))
)

server <- function(input, output, session) {
  freezeReactiveValue(input, "col")
  
  # server-side selectize for improved performance
  updateSelectizeInput(
    session,
    "col",
    choices = DF$country,
    selected = DF$country[1],
    server = TRUE
  )
  
  observeEvent(input$col, {
    updateCheckboxGroupInput(
      session,
      "chk",
      "Select item to plot",
      choices = input$col,
      selected = input$col
    )
  })
  
  output$tseries <- renderPlotly({
    if (is.null(input$chk)) {
      plotly_empty(type = 'scatter', mode = 'lines')
    } else {
      plot_ly(
        DF[DF$country %in% input$chk, ],
        type = 'scatter',
        mode = 'lines',
        x = ~ year,
        y = ~ lifeExp,
        split = ~ country
      )
    }
  })
}

shinyApp(ui, server)

As mentioned above this is a duplicate of my earlier answer here.

However, @YBS' approach is overly complex and I'd like to provide the possibility for a direct comparison. Using a data.frame in long format for ggplot or plotly is the preferred way to go (Use e.g. data.table::melt to convert from wide to long). This way we can use plot_ly's split, name or color parameter to create multiple traces based on the data:

library(shiny)
library(shinydashboard)
library(plotly)
library(gapminder)

DF <- gapminder[, c(1, 3, 4)]

ui <- dashboardPage(
  dashboardHeader(),
  dashboardSidebar(
    selectizeInput(
      "col",
      "Pick a column for y-axis to plot, if ticked in checkbox below",
      choices = NULL,
      selected = NULL,
      multiple = TRUE
    ),
    checkboxGroupInput("chk", "Display Plot", choices = DF$country[1])
  ),
  dashboardBody(tabsetPanel(id = "tabs",
                            tabPanel(
                              "Plot data" , plotlyOutput("tseries")
                            )))
)

server <- function(input, output, session) {
  freezeReactiveValue(input, "col")
  
  # server-side selectize for improved performance
  updateSelectizeInput(
    session,
    "col",
    choices = DF$country,
    selected = DF$country[1],
    server = TRUE
  )
  
  observeEvent(input$col, {
    updateCheckboxGroupInput(
      session,
      "chk",
      "Select item to plot",
      choices = input$col,
      selected = input$col
    )
  })
  
  output$tseries <- renderPlotly({
    if (is.null(input$chk)) {
      plotly_empty(type = 'scatter', mode = 'lines')
    } else {
      plot_ly(
        DF[DF$country %in% input$chk, ],
        type = 'scatter',
        mode = 'lines',
        x = ~ year,
        y = ~ lifeExp,
        split = ~ country
      )
    }
  })
}

shinyApp(ui, server)
看透却不说透 2025-01-26 08:27:16

一种方法是通过selectInput选择所有可以包含在时间序列中的变量。然后绘制旁边有复选标记的那些。完整代码。

library(shiny)
library(shinydashboard)
library(DT)
library(plotly)
library(gapminder)
library(tidyr)

dfa <- gapminder[,c(1,3,4)]

df <- dfa %>% pivot_wider(names_from = country, values_from = lifeExp)

cols <- colnames(df)[-1]

ui <- dashboardPage(
  dashboardHeader(),
  dashboardSidebar(
    selectInput("col","Pick a column for y-axis to plot, if ticked in checkbox below", choices = cols, selected = cols[1], multiple = TRUE),
    checkboxGroupInput("chk", "Display Plot", choices = cols[1]) 
  ),
  dashboardBody(
    tabsetPanel(id="tabs",
                tabPanel("Plot data" , plotlyOutput("tseries"))
    ))
)

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

  observeEvent(input$col, {
    
    updateCheckboxGroupInput(session, "chk","Select item to plot", choices = input$col)
    
  })
  
  output$tseries <- renderPlotly({

    if (is.null(input$chk)) { ### nothing selected to plot
      fig <- NULL
    }else {
      n <- length(input$chk)
      lapply(1:n, function(i) {
        if (i==1){ ### one item plot
          fig <<- plot_ly(df, type = 'scatter', mode = 'lines') %>%
            add_trace(x = ~year, y = ~.data[[input$chk[1]]], showlegend = F)
        }else { ### additional items to plot
          fig <<- fig %>%  add_trace(x = ~year, y = ~.data[[input$chk[i]]], showlegend = F)
        }
      })
      
    }

    fig
  })

}

shinyApp(ui, server)

One way to do it is to select all the variables that could be included in the time series via selectInput. Then plot the ones that have a check mark next to them. Full code.

library(shiny)
library(shinydashboard)
library(DT)
library(plotly)
library(gapminder)
library(tidyr)

dfa <- gapminder[,c(1,3,4)]

df <- dfa %>% pivot_wider(names_from = country, values_from = lifeExp)

cols <- colnames(df)[-1]

ui <- dashboardPage(
  dashboardHeader(),
  dashboardSidebar(
    selectInput("col","Pick a column for y-axis to plot, if ticked in checkbox below", choices = cols, selected = cols[1], multiple = TRUE),
    checkboxGroupInput("chk", "Display Plot", choices = cols[1]) 
  ),
  dashboardBody(
    tabsetPanel(id="tabs",
                tabPanel("Plot data" , plotlyOutput("tseries"))
    ))
)

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

  observeEvent(input$col, {
    
    updateCheckboxGroupInput(session, "chk","Select item to plot", choices = input$col)
    
  })
  
  output$tseries <- renderPlotly({

    if (is.null(input$chk)) { ### nothing selected to plot
      fig <- NULL
    }else {
      n <- length(input$chk)
      lapply(1:n, function(i) {
        if (i==1){ ### one item plot
          fig <<- plot_ly(df, type = 'scatter', mode = 'lines') %>%
            add_trace(x = ~year, y = ~.data[[input$chk[1]]], showlegend = F)
        }else { ### additional items to plot
          fig <<- fig %>%  add_trace(x = ~year, y = ~.data[[input$chk[i]]], showlegend = F)
        }
      })
      
    }

    fig
  })

}

shinyApp(ui, server)

output

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文