闪亮 - 如果没有使用滑块选择数据,如何防止绘图

Shiny - how to prevent plotting if no data is selected with the slider

我想在我的 Shiny App 中绘制一个 plotly 3D 图形,但只绘制值在输入范围滑块范围内的数据。但是,当滑块范围内没有值时,我想阻止绘图 - 当前,当没有输入时,这会导致以下错误:

Warning: Error in UseMethod: no applicable method for 'plotly_build' applied       
to an object of class "NULL"

或在示例代码中:

Error in : length(Lab) == 3L is not TRUE

这是一个示例代码,与原始问题有类似的错误:

library(shiny)
library(plotly)

d = diamonds[1:100,]

ui = fluidPage(
headerPanel("Data"),

sliderInput(inputId="slider", label = "Choose a range", value =c(0,max(d$price)),
          min = 0,max = max(d$price)),

# saves space for the plot in the user interface. Id allows communication
plotlyOutput(outputId="trendPlot", width="100%", height=800)

)

server = function(input, output)
{
NROF = reactiveValues(test = 1)

output$trendPlot= renderPlotly({
d_sub=d[d$price >= input$slider[1] & d$price <= input$slider[2],]
NROF = nrow(d) 
if(NROF != 0)
{
  plot_ly(d_sub, x=d_sub$cut, y=d_sub$color, z=factor(d_sub$color),
          type='scatter3d', mode='markers',
          sizemode='diameter', size=d_sub$price, color=d_sub$price,colors = 'Set1')

}
})
}

shinyApp(ui=ui, server=server)

解决方案:我在使用反应值时犯了一个错误 - 它应该是 NROF$TEST

我试着重现了它。我的建议是有一个小错字(你的意思是 NROF = nrow(d_sub) 而不是 NROF = nrow(d))。另外,您没有为 else 案例包含任何 return 值。

这对你有帮助吗?

server = function(input, output)
{
  NROF = reactiveValues(test = 1)

  output$trendPlot= renderPlotly({
    d_sub=d[d$price >= input$slider[1] & d$price <= input$slider[2],]
    NROF = nrow(d_sub)
    if(NROF != 0)
    {
      plot_ly(d_sub, x=d_sub$cut, y=d_sub$color, z=factor(d_sub$color),
              type='scatter3d', mode='markers',
              sizemode='diameter', size=d_sub$price, color=d_sub$price,colors = 'Set1')

    } else {
      plot_ly(type='scatter3d')
    }
  })
}

听起来像 req()validate() 是您要查找的内容:

http://shiny.rstudio.com/articles/req.html

http://shiny.rstudio.com/articles/validation.html

library(shiny)
library(plotly)

d <- diamonds[1:100,]

ui <- fluidPage(
  headerPanel("Data"),
  sliderInput(inputId="slider",
              label = "Choose a range",
              value =c(0,max(d$price)),
              min = 0,max = max(d$price)),
  # saves space for the plot in the user interface. Id allows communication
  plotlyOutput(outputId="trendPlot",
               width="100%", height=800)

)

server <- function(input, output) {
  output$trendPlot <- renderPlotly({
    d_sub <- d[d$price >= input$slider[1] & d$price <= input$slider[2],]
    req(nrow(d_sub) > 0)
    # validate(need(nrow(d_sub) > 0, "No data selected!"))

    plot_ly(d_sub, x=d_sub$cut, y=d_sub$color, 
            z=factor(d_sub$color), type='scatter3d', 
            mode='markers', sizemode='diameter', 
            size=d_sub$price, color=d_sub$price,
            colors = 'Set1')
  })
}

shinyApp(ui=ui, server=server)