-->

How to Export ggplotly from R shiny app as html fi

2019-07-26 16:44发布

问题:

I have a ggplotly object called p2 in my shiny app. I want it to work where if a user presses a downloadButton in the app UI, it will download the ggplotly plot as an html file. But the function doesn't work:

output$Export_Graph <- downloadHandler(

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

      },

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

Any ideas?

回答1:

An interactive plotly graph can be exported as an "html widget". A minimal sample code is like the following:

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)

Note: Before run the code, pandoc have to be installed. See http://pandoc.org/installing.html



标签: r ggplotly