首页 > 解决方案 > 如何在 R Shiny Dashboard 中打开和关闭线条

问题描述

我正在使用 R Shiny 中的 Plot_ly 包绘制图表。现在我正在创建一个上面有很多线条的图表,我想知道用户是否可以使用复选框输入来打开和关闭线条。

这是我的服务器端代码示例:

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

})

对于我的 ui 方面,我创建了这样的复选框:

fluidRow(checkboxInput("Actuals", "Actual Line", value = TRUE))

有没有办法可以使用此复选框输入来打开和关闭实际行?我一直在尝试在 add_lines 命令之前使用 if 语句,但我收到一个错误,指出它不合逻辑。

标签: rshiny

解决方案


您可以存储第一组行并根据复选框触发的条件添加第二组。如果没有可重复的示例,很难提出一个可行的解决方案,但这样的事情应该可以完成:

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)

})

推荐阅读