【问题标题】:R Shiny: How not to display plot when NULLR Shiny:NULL时如何不显示绘图
【发布时间】:2021-02-01 00:45:48
【问题描述】:

如果您在 R 工作室中运行此代码,您会发现 NULL 数据的绘图仍然是一大块白色。

data 为 NULL 时怎么不显示呢。

在其他图表中,大白板看起来并不那么好。

library(shiny)

server <- function(input, output) {
  output$x = renderPlot(NULL)
}

ui <- fluidPage(
  br(),
  plotOutput("x"),
  tags$head(tags$style(HTML("
                            body {
                            margin: 0;
                            font-family: helvetica, sans-serif;
                            background: #F2F0F0;
                            }

                            .shiny-plot-output{
                            max-width: 100%;
                            box-shadow: 0px 0px 6px #888;
                            margin-left: auto;
                            margin-right: auto;
                            }
                            ")))  
  )

shinyApp(ui = ui, server = server)

【问题讨论】:

    标签: r shiny


    【解决方案1】:

    我找到了另一种解决方案(因为上述解决方案对我不起作用)。它使用了shinyjs 包。这是一个最小的可重现示例。

    library(shinyjs)
    library(shinythemes)
    
    
    shinyApp(
      ui = fluidPage(theme = shinytheme("darkly"),
                     useShinyjs(), # IMPORTANT, you have to call this function in your UI to use shinyjs
                     numericInput("num","Number", 5),
                     plotOutput("text1")
      ),
      server = function(input, output) {
        
        observe({
          if (input$num < 5) {
            hide("text1")
          } else {
            show("text1")
          }
        })
        
        output$text1 <- renderPlot({
          plot(rnorm(input$num))
        })
      }
    )
    

    仅当 x > 5 时才显示该图。否则该图(以及空格 - 此处使用闪亮主题中的 darkly 主题突出显示 - 不存在)

    【讨论】:

    • 在我的最后,一旦情节被隐藏,它就不会再次出现。即使您将数字输入更改为 >5。
    • 解决了吗?有没有办法让情节在 x>5 时再次出现?
    • @Oshan 我编辑了答案,将条件测试放在观察者中。因此,当数字再次超过 5 时,图形再次出现。
    【解决方案2】:

    你可以在 server.R 中做这样的事情:

      if(is.null(df)){}
      else{
      output$x = renderPlot(df)
      }
    

    这将检查您发送给renderPlot 的数据是否为NULL,并且仅在数据存在时才执行renderPlot。这可能会使画布看起来不是白色,而是灰色背景。唯一的问题是,当您制作阴影效果时,它也会出现在灰色上。

    【讨论】:

    • 但是如果数据为NULL,ui.R中的plotOutput("x")会报错,在ui.R中不能使用if else语句,对吧?
    • 添加此文本后,我没有注意到输出有任何差异。 @John 这解决了你的问题吗?
    • 我使用renderUIif语句来动态调整图表的高度。这工作得很好,但不是很优雅,因为我必须用renderUI 包装每个图表。
    猜你喜欢
    • 1970-01-01
    • 2014-08-21
    • 2018-04-06
    • 1970-01-01
    • 2022-07-22
    • 2018-04-27
    • 1970-01-01
    • 1970-01-01
    • 2011-05-13
    相关资源
    最近更新 更多