Reputation: 51
I am plotting a graph using the Plot_ly package in R Shiny. Right now I am creating a graph with many lines on it and I would like to know if it is possible for the user to toggle the lines on and off using the checkbox input.
Here is a sample of my server side code:
output$site_filter <- renderUI({
selectInput("site_filter", "Sites"
sort(unique(site_list$sites), decreasing = FALSE))
})
output$plots <- renderPlotly({
forecast_detail <- forecast[forecast$site == input$site_filter,]
actual_detail <- actual[actual$site == input$site_filter,]
p <- plot_ly() %>%
add_lines(x = forecast_detail$date, y = forecast_detail$total,
name = 'Forecast', line = list(color = 'purple')) %>%
add_lines(x = actual_detail$date, y = actual_detail$total,
name = 'Actual', line = list(color = 'blue'))
})
For my ui side, I created the checkbox like this:
fluidRow(checkboxInput("Actuals", "Actual Line", value = TRUE))
Is there a way I could use this checkbox input to toggle the actual lines on and off? I've been trying to use an if statement before the add_lines command but I get an error that states it is not logical.
Upvotes: 1
Views: 565
Reputation: 2864
You can store the first group of lines and add the second group based on a condition triggered by your checkbox. It is hard to come up with a working solution without a reproducible example but something like this should do the job:
output$plots <- renderPlotly({
forecast_detail <- forecast[forecast$site == input$site_filter,]
actual_detail <- actual[actual$site == input$site_filter,]
p <- plot_ly() %>%
add_lines(
x = forecast_detail$date,
y = forecast_detail$total,
name = 'Forecast',
line = list(color = 'purple')
)
if(!is.null(input$Actuals)) {
p <- p %>%
add_lines(
x = actual_detail$date,
y = actual_detail$total,
name = 'Actual',
line = list(color = 'blue')
)
}
return(p)
})
Upvotes: 1