简体   繁体   English

如何将 R Shiny 中的 Dygraphs 保存为 PNG?

[英]How save Dygraphs in R Shiny as PNG?

How to save "dygraphs" plots as PNG in R Shiny app.如何在 R Shiny 应用程序中将“dygraphs”绘图保存为 PNG。

library(shiny)
library(dygraphs)

ui <- shinyUI(
  fluidPage(
    titlePanel("How save Dygraphs in R Shiny as PNG"),
    mainPanel(
      dygraphOutput("plot_dy")
    )
  )
)
server <- function(input, output, session) {
  
  output$plot_dy <- renderDygraph({
    
    # 1. Data set
    lungDeaths <- cbind(mdeaths, fdeaths)
    
    # 2. Plot
    g <- dygraph(lungDeaths)
    
    # 3. How to save plot here as PNG ?
    
    # 4. Result
    g
    
  })
  
}

shinyApp(ui,server)

Thanks!谢谢!

library(shiny)
library(dygraphs)
library(htmlwidgets)

# download "dygraph-extra.js" at
# https://cavorite.com/labs/js/dygraphs-export/dygraph-extra.js
# and put this file in the www subfolder

js <- HTML(
  'function Export() {',
  '  const a = document.createElement("a");',
  '  document.body.append(a);',
  '  a.download = "dygraph.png";',
  '  a.href = $("img").attr("src");',
  '  a.click();',
  '  a.remove();',
  '}'
)

ui <- fluidPage(
  tags$head(tags$script(js)),
  tags$img(id = "img", style = "display: none;"),
  br(),
  actionButton("export", "Export to PNG", onclick = "Export();"),
  br(),
  dygraphOutput("dygraph"),
  tags$script(src = "dygraph-extra.js")
)

server <- function(input, output, session){

  output[["dygraph"]] <- renderDygraph({
    lungDeaths <- cbind(mdeaths, fdeaths)
    dygraph(lungDeaths) %>%
      onRender(c(
        "function(el,x) {",
        "  Dygraph.Export.asPNG(", # more options: https://cavorite.com/labs/js/dygraphs-export/
        "    this.dygraph, document.getElementById('img'), {backgroundColor: 'white'}",
        "  );",
        "}"
      ))
  })

}

shinyApp(ui, server)

Here is a solution I design for "plotly" and "dygraph" packages这是我为“plotly”和“dygraph”包设计的解决方案

#
# Download PNG files via R Shiny 'downloadHandler'
#

library(shiny)
library(plotly)
library(dygraphs)
library(png)
library(htmlwidgets)
library(webshot2)

# Save PNG file on disk
export <- function(plot_name, file_name = "file_name.png", ...) {
  if(system.file(package = "webshot") == "") {
    stop(
      'Please install the webshot package ',
      '(if not on CRAN, try devtools::install_github("wch/webshot"))')
  }
  file_name_temp_html <- basename(tempfile('file_temp', '.', '.html'))
  on.exit(unlink(file_name_temp_html), add = TRUE)
  html <- htmlwidgets::saveWidget(plot_name, file_name_temp_html)
  webshot2::webshot(file_name_temp_html, file_name, ...)
}

# UI ----------
ui <- fluidPage(
  # 1. Plotly
  plotlyOutput("plotly_view"),
  downloadButton("btn_download_plotly", "Download"),
  
  # 2. Dygraphs
  dygraphOutput("dygraph_view"),
  downloadButton("btn_download_dygraph", "Download")
)

# SERVER ----------
server <- function(input, output, session) {
  
  # 1. PLOTLY -------
  
  # 1.1. Create 'Plotly' view
  create_plotly <- reactive({
    set.seed(100)
    df <- diamonds[sample(nrow(diamonds), 1000), ]
    g <- plot_ly(
      df, x = df$carat, y = df$price, text = paste("Clarity: ", df$clarity),
      mode = "markers", color = df$carat, size = df$carat)
    g <- ggplotly(g, tooltip = c("text")) %>% config(displayModeBar = FALSE)
    g
  })
  
  # 1.2. Render 'Plotly' view
  output$plotly_view <- renderPlotly({
    create_plotly()
  })
  
  # 1.3. Download plot
  output$btn_download_plotly <- downloadHandler(
    filename = "plotly_view.png",
    content = function(file) {
      
      # 1. File name for temp file
      file_temp_png <- paste0("tmp_", Sys.Date(), ".png")
      
      # 1. Create file on disk
      export(create_plotly(), file_temp_png)
      
      # 2. Export
      file.copy(file_temp_png, file, overwrite=TRUE)
      
      # 3. Drop file
      file.remove(file_temp_png)
      
    }
  )
  
  # 2. DYGRAPH ------
  
  # 2.1. Create 'Dygraph' view
  create_dygraph <- reactive({
    set.seed(100)
    df <- cbind(mdeaths, fdeaths)
    g <- dygraph(df)
    g
  })
  
  # 2.2. Render 'Dygraph' view
  output$dygraph_view <- renderDygraph({
    create_dygraph()
  })
  
  # 2.3. Download plot
  output$btn_download_dygraph <- downloadHandler(
    filename = "dygraph_view.png",
    content = function(file) {
      
      # 1. File name for temp file
      file_temp_png <- paste0("tmp_", Sys.Date(), ".png")
      
      # 1. Create file on disk
      export(create_dygraph(), file_temp_png)
      
      # 2. Export
      file.copy(file_temp_png, file, overwrite=TRUE)
      
      # 3. Drop file
      file.remove(file_temp_png)
      
    }
  )
}

shinyApp(ui, server)

Hope it will be useful!希望它会很有用!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM