How to Export ggplotly from R shiny app as html file

北慕城南 提交于 2019-12-09 06:10:42

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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!