ggplotly没有适用于"class NULL"对象的'plotly_build'方法。if语句。

3
在将 Plotly 集成到闪亮仪表板中时,试图使用条件语句通过 selectInput 切换图表时遇到错误。我已经成功地使用 circlize 包和 ggplot 图形,但是在尝试使用 Plotly 时,出现以下错误:
"Error in UseMethod: no applicable method for 'plotly_build' applied to an object of class "NULL"
我在此处找到了一个与此类似但并未完全解决我的问题的帖子:
Convert ggplot object to plotly in shiny application
下面是一个示例,其中使用了与上述帖子类似的代码,但进行了修改以展示我想要做的事情以及不断弹出的错误提示。
library(shiny)
library(ggplot2)
library(ggthemes)
library(plotly)
ui = dashboardPage(
    dashboardHeader(title = 'sample'),
    dashboardSidebar(), ##Body content dashboardBody(
        fluidRow(
            box(background = "green", selectInput(inputId = "dimension",
                label = strong("Choose Metric"),
                choices = c('choice' = '1', 'choice2' = '2'),
                multiple = FALSE, selectize = TRUE)),

            box(plotlyOutput(outputId = 'plot2')))
    ))

server < - function(input, output) {

    output$plot2 < -renderPlotly({
        print(
            ggplotly(
                ggplot(data = mtcars, aes(x = disp, y = cyl)) + geom_smooth(method =
                    lm, formula = y~x) + geom_point() + theme_gdocs()))

        if (input$dimension == '2') {
            print(
                ggplotly(
                    ggplot(data = mtcars, aes(x = hp, y = cyl)) + geom_smooth(method =
                        lm, formula = y~x) + geom_point() + theme_gdocs()))

        }
    })
}

shinyApp(ui, server)

我还在学习中,所以肯定会有一些简单的错误逃过我的注意,但是我不确定它可能是什么。感谢您的帮助!

1个回答

3
简单来说,问题在于如果input$dimension'1'时没有返回值。你只是将图形打印出来,但R会进一步检查是否满足条件。有几种正确的编码方式。
可以将绘图保存在一个对象中,比如res,如果满足条件,则用新的绘图覆盖它,并最终在函数末尾返回它——请参见下面的示例。你也可以使用else语句。
library(shiny)
library(shinydashboard)
library(ggplot2)
library(ggthemes)
library(plotly)

ui = dashboardPage(
  dashboardHeader(title = 'sample') ,
  dashboardSidebar(),
  ## Body content
  dashboardBody(
    fluidRow(
      box(background="green", selectInput(inputId = "dimension", 
                                          label = strong("Choose Metric"),
                                          choices = c('choice'='1','choice2'='2'), 
                                          multiple = FALSE, selectize = TRUE)),

      box(plotlyOutput(outputId = 'plot2')))
  ))

server <- function(input, output) {

  output$plot2 <- renderPlotly({

    res <- ggplotly(
              ggplot(data = mtcars, aes(x = disp, y = cyl)) + 
                geom_smooth(method = lm, formula = y ~ x) + 
                geom_point() + 
                theme_gdocs())


    if (input$dimension == '2') {

      res <- ggplotly(
                ggplot(data = mtcars, aes(x = hp, y = cyl)) +  
                  geom_smooth(method = lm, formula = y ~ x) + 
                  geom_point() + 
                  theme_gdocs())
    }
    res
  })
}

shinyApp(ui, server)

1
这太完美了,运行得非常棒。非常感激您的帮助! - LoF10

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接