【问题标题】:plotly::renderPlotly() does not allow for NULL values. How can I workaround?plotly::renderPlotly() 不允许 NULL 值。我该如何解决?
【发布时间】:2018-02-16 12:45:08
【问题描述】:

标题基本上是这样说的。对于复杂的 Shiny App,我必须能够将 NULL 值发送到 renderPlotly(),因为我只想在满足某些条件时才显示绘图。普通的shiny::renderPlot() 能够做到这一点。 一个给出我不想要的错误的小例子:

library(shiny)
library(plotly)

ui <- fluidPage(
  plotlyOutput("plotly"),
  plotOutput("plot")
)

server <- function(input, output) {

  # I need to be able to put NULL in here or anything so that
  # there is no output and also no error message.
  output$plotly <- renderPlotly({
    NULL
  })

  # This works and sends no error message
  output$plot <- renderPlot({
    NULL
  })

}

shinyApp(ui, server)

请注意,Web 应用程序仅显示一条错误消息,即来自 renderPlotly() 的一条错误消息。 我正在寻找任何解决方法。如何在应用程序的同一位置显示的这两个图之间切换,并始终忽略其中一个,具体取决于其他输入?

【问题讨论】:

标签: r shiny plotly


【解决方案1】:

当您的数据为空时,您可以使用 plotly_empty() 函数。

假设您将您的 plotly(或 NULL)分配给一个名为“myplotly”的变量,您可以使用以下内容:

  output$plotly <- renderPlotly({
    if(is.null(myplotly)) plotly_empty() else myplotly
  })

【讨论】:

    【解决方案2】:

    使用shiny::conditionalPanel 的示例。仅当满足特定条件时才会显示绘图。

    library(ggplot2)
    library(plotly)
    library(shiny)
    
    ui <- fluidPage(
        selectInput("shouldShow", "show plot", c("yes", "no"), "yes"),
        conditionalPanel(
            condition = "input.shouldShow == 'yes'",
            plotlyOutput("foo")
        )
    )
    
    server <- function(input, output) {
        output$foo <- renderPlotly({
            gg <- ggplot(mtcars, aes(cyl, mpg)) + geom_point()
            ggplotly(gg)
        })
    }
    shinyApp(ui, server)
    

    【讨论】:

    • 感谢您的回答。但是条件面板是否可能取决于在服务器部分创建的条件?
    • @Stan125 是的。你能举例说明“在服务器中”是什么意思吗?如果加载的文件大小大于什么或什么?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-26
    • 2020-01-16
    • 2021-06-18
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    • 2012-11-18
    相关资源
    最近更新 更多