在闪亮的应用程序中将 ggplot 对象转换为 plotly

Convert ggplot object to plotly in shiny application

我正在尝试将 ggplot 对象转换为 plotly 并在闪亮的应用程序中显示它。但是我遇到了错误 "no applicable method for 'plotly_build' applied to an object of class "NULL""

我能够 return 成功地将 ggplot 对象添加到闪亮的应用程序,

output$plot1 <- renderplot({
   gp <- ggplot(data = mtcars, aes(x = disp, y = cyl)) + geom_smooth(method = lm, formula = y~x) + geom_point() + theme_gdocs()
})

但不知何故无法转换它。

我的代码是这样的

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

尝试:

library(shiny)
library(ggplot2)
library(ggthemes)
library(plotly)

ui <- fluidPage(  
titlePanel("Plotly"),
sidebarLayout(
sidebarPanel(),
mainPanel(
  plotlyOutput("plot2"))))
  
server <- function(input, output) {

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

shinyApp(ui, server)

如果它在 RStudio 窗格而不是应用程序中呈现,请确保您在 UI 部分中使用 plotlyOutput 以及在服务器部分中使用 renderPlotly .