首页 > 解决方案 > 根据复选框在 plotOutput 和 plotlyOutput 之间切换

问题描述

我正在尝试构建一个 Shiny 应用程序,该应用程序仅plotly在用户为交互式图形标记复选框时才加载。但是,到目前为止,我尝试过的最终都绘制了两个数字,而不管复选框值如何:

require('plotly')
require('shiny')

ui <- fluidPage(

  tabsetPanel(
    id = 'mainTab',

    tabPanel(
      'conditionally interactive tab',

      checkboxInput(
        inputId = 'interactive', label = 'Interactive figure', value = FALSE
      ),

      conditionalPanel(
        condition = 'input.interactive == TRUE',
        plotlyOutput('interactivePlot')
      ),

      conditionalPanel(
        condition = 'input.interactive == FALSE',
        plotOutput('staticPlot')
      )
    ),
    tabPanel('unrelated tab')
  )
)

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

  output$interactivePlot <- renderPlotly({
    plot_ly(iris, x = ~Petal.Length, y = ~Sepal.Length)
  })

  output$staticPlot <- renderPlot({
    plot(Sepal.Length ~ Petal.Length, iris)
  })
}

shinyApp(ui = ui, server = server)

造成这种情况的原因是使用 plotly 时加载时间较长,以及在手持设备上使用 plotly 的不便(尝试使用对触摸有反应的绘图滚动很困难)。我不想为它们设置单独的选项卡,但我意识到如果没有其他方法可行,那可能是一种选择。

标签: rplotshinyplotly

解决方案


你很亲密。条件condition面板中的表达式是 JavaScript 表达式,也不是 R 表达式。在 JavaScript 中,他们使用true/false而不是TRUE/ FALSE。所以只要改变它,它就会起作用。

require('plotly')
require('shiny')

ui <- fluidPage(

        tabsetPanel(
                id = 'mainTab',

                tabPanel(
                        'conditionally interactive tab',

                        checkboxInput(
                                inputId = 'interactive', label = 'Interactive figure', value = FALSE
                        ),

                        conditionalPanel(
                                condition = 'input.interactive == true',
                                plotlyOutput('interactivePlot')
                        ),

                        conditionalPanel(
                                condition = 'input.interactive == false',
                                plotOutput('staticPlot')
                        )
                ),
                tabPanel('unrelated tab')
        )
)

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

        output$interactivePlot <- renderPlotly({
                plot_ly(iris, x = ~Petal.Length, y = ~Sepal.Length)
        })

        output$staticPlot <- renderPlot({
                plot(Sepal.Length ~ Petal.Length, iris)
        })
}

shinyApp(ui = ui, server = server)

推荐阅读