简体   繁体   中英

R plotly to add traces conditionally based on available columns in dataframe

I have a dataframe in my Shiny app that gets filtered based on various user inputs.

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)))

})

In the next step, I pass this filtered dataframe through a plot_ly function

Here is where I need help

I am trying to get plot_ly to conditionally add lines (add traces) , based on whether the given column is available in the dataframe or not . At the moment, plot_ly throws an error if any of the columns included in the add_trace s is not available after the dataframe is filtered.

Here is the part of my Shiny app with the plot_ly output. I attempted to add if-else statements between the add_trace arguments, but my attempts haven't been successful.

 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"))

})

My apologies for not being able to include a reproducible dataframe, I realise that would make things easier. Very grateful for any tips/pointers you might have.

One way to do it could be to use a for loop to add a trace per column

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"))
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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