如何将 ggplotly 从 R闪亮应用程序导出为 html 文件

kar*_*uno 1 r ggplotly

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

output$Export_Graph <- downloadHandler(

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

      },

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

Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

tas*_*aki 5

交互式绘图可以导出为“html 小部件”。最小的示例代码如下:

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)
Run Code Online (Sandbox Code Playgroud)

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