【问题标题】:R plotly to add traces conditionally based on available columns in dataframeR plotly 根据数据框中的可用列有条件地添加跟踪
【发布时间】:2017-10-05 10:21:12
【问题描述】:

我的 Shiny 应用中有一个数据框,它会根据各种用户输入进行过滤。

global_evolution=reactive({

  results_combined %>%
  filter(!is.na(SVM_LABEL_QOL) & SVM_LABEL_QOL=='QoL' & globalsegment==input$inp_pg1segment & Account==input$inp_pg1clientsfiltered & Date >=input$inp_pg1daterange[1] & Date <=input$inp_pg1daterange[2]) %>% #Inputs
  select(Account,Date,SVM_LABEL_DIMENSION) %>%
  mutate(Month=month(as.Date(format(as.POSIXct(Date),format = "%d/%m/%Y"),"%d/%m/%Y"))) %>%
  select(Account,Month,SVM_LABEL_DIMENSION,-Date) %>%
  group_by(Month,SVM_LABEL_DIMENSION) %>%
  summarise(Monthly_Count=n()) %>%
  spread(SVM_LABEL_DIMENSION,Monthly_Count) %>%
  ungroup() %>%
  mutate(Month=month.abb[Month]) %>%
  mutate_all(funs(replace(., is.na(.), 0)))

})

在下一步中,我将这个过滤后的数据帧传递给 plot_ly 函数

这是我需要帮助的地方

我试图让plot_ly 有条件地添加行(添加跟踪),这取决于给定列在数据框中是否可用。目前,如果 add_traces 中包含的任何列在过滤数据帧后不可用,plot_ly 将引发错误。

这是我的 Shiny 应用程序的一部分,带有 plot_ly 输出。 我试图在add_trace 参数之间添加if-else 语句,但我的尝试没有成功。

 output$pg1evolution <- renderPlotly({

global_evolution_final() %>%
plot_ly(x = ~Month, y = ~`COLUMN_1`, name = 'Column 1', type = 'scatter', mode = 'lines') %>%
add_trace(y = ~`COLUMN_2`, name = 'Column 2') %>%
add_trace(y = ~`COLUMN_3`, name = 'Column 3') %>%
add_trace(y = ~`COLUMN_4`, name = 'Column 4') %>%
add_trace(y = ~`COLUMN_5`, name = 'Column 5') %>%
add_trace(y = ~`COLUMN_6`, name = 'Column 6') %>%
layout(title = "Trend Over Time",
       xaxis = list(title = ""),
       yaxis = list (title = "Monthly Count of Products Sold"))

})

对于无法包含可重现的数据框,我深表歉意,我意识到这会使事情变得更容易。 非常感谢您提供的任何提示/指示。

【问题讨论】:

    标签: r shiny plotly


    【解决方案1】:

    一种方法是使用 for 循环为每列添加一个跟踪

    output$pg1evolution <- renderPlotly({
    
    colNames <- names(global_evolution_final())[-1] #Assuming Month is the first column
    
    p <- plotly::plot_ly(data = global_evolution_final(), x = ~Month, type = "scatter",
                         mode = "lines")
    
    for(trace in colNames){
        p <- p %>% plotly::add_trace(y = as.formula(paste0("~`", trace, "`")), name = trace)
    }
    
    p %>% 
    layout(title = "Trend Over Time",
           xaxis = list(title = ""),
           yaxis = list (title = "Monthly Count of Products Sold"))
    })
    

    【讨论】:

    • 优雅的解决方案。谢谢耐克特!
    • Niket 我对你的代码做了一个小的修改,type='bar' 而不是折线图。但是,当我绘制它时,我在图例中看到“trace 0”以及其他列名。你知道这是从哪里来的吗?
    猜你喜欢
    • 2020-02-12
    • 2022-07-01
    • 2021-10-26
    • 2022-01-09
    • 2019-07-14
    • 1970-01-01
    • 2016-04-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多