如何从 R shiny 应用程序导出 ggplotly 作为 html 文件

How to Export ggplotly from R shiny app as html file

我的闪亮应用程序中有一个名为 p2 的 ggplotly 对象。我希望它在用户按下应用程序 UI 中的下载按钮的情况下工作,它会将 ggplotly 图下载为 html 文件。但该功能不起作用:

output$Export_Graph <- downloadHandler(

      filename = function() {
        file <- "Graph"

      },

      content = function(file) {
        write(p2, file)
      }

有什么想法吗?

交互式绘图可以导出为 "html widget"。 最小示例代码如下所示:

library(shiny)
library(plotly)
library(ggplot2)
library(htmlwidgets) # to use saveWidget function

ui <- fluidPage(

    titlePanel("Plotly html widget download example"),

    sidebarLayout(
        sidebarPanel(
            # add download button
            downloadButton("download_plotly_widget", "download plotly graph")
        ),

        # Show a plotly graph 
        mainPanel(
            plotlyOutput("plotlyPlot")
        )
    )

)

server <- function(input, output) {

    session_store <- reactiveValues()

    output$plotlyPlot <- renderPlotly({

        # make a ggplot graph
        g <- ggplot(faithful) + geom_point(aes(x = eruptions, y = waiting))

        # convert the graph to plotly graph and put it in session store
        session_store$plt <- ggplotly(g)

        # render plotly graph
        session_store$plt
    })

    output$download_plotly_widget <- downloadHandler(
        filename = function() {
            paste("data-", Sys.Date(), ".html", sep = "")
        },
        content = function(file) {
            # export plotly html widget as a temp file to download.
            saveWidget(as_widget(session_store$plt), file, selfcontained = TRUE)
        }
    )
}

# Run the application 
shinyApp(ui = ui, server = server)

注意: 在 运行 代码之前,必须安装 pandoc。 参见 http://pandoc.org/installing.html