繁体   English   中英

R Shiny:如何在为 NULL 时不显示绘图

[英]R Shiny: How not to display plot when NULL

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

当数据为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)

我找到了另一种解决方案(因为上面的解决方案对我不起作用)。 它使用了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 时显示。否则该图(以及空白 - 此处通过使用 Shinythemes 中的darkly主题突出显示 - 不存在)

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM