Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
303 views
in Technique[技术] by (71.8m points)

r - Download Plotly using downloadHandler

i got stuck at some point while trying to use downloadHandler to download Plotly images. I just cannot figure out further how to get the image from temp directory...

Here is a sample code:

library(shiny)
library(plotly)
library(rsvg)
library(ggplot2)

d <- data.frame(X1=rnorm(50,mean=50,sd=10),X2=rnorm(50,mean=5,sd=1.5),Y=rnorm(50,mean=200,sd=25))

ui <-fluidPage(
  title = 'Download Plotly',
  sidebarLayout(

    sidebarPanel(
      helpText(),
      downloadButton('download'),
      tags$script('
                  document.getElementById("download").onclick = function() {
                  var plotly_svg = Plotly.Snapshot.toSVG(
                  document.querySelectorAll(".plotly")[0]
                  );

                  Shiny.onInputChange("plotly_svg", plotly_svg);
                  };
                  ')
      ),
    mainPanel(
      plotlyOutput('regPlot'),
      plotlyOutput('regPlot2')
    )
      )
)

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

  output$regPlot <- renderPlotly({
    p <- plot_ly(d, x = d$X1, y = d$X2,mode = "markers")
    p
  })

  output$regPlot2 <- renderPlotly({
    p <- plot_ly(d, x = d$X1, y = d$X2,mode = "markers")
    p
  })

  observeEvent(input$plotly_svg, priority = 10, {
    png_gadget <- tempfile(fileext = ".png")
    png_gadget <- "out.png"
    print(png_gadget)
    rsvg_png(charToRaw(input$plotly_svg), png_gadget)
  })

  output$download <- downloadHandler(
    filename = function(){
      paste(paste("test",Sys.Date(),sep=""), ".png",sep="")},
    content = function(file) {
      temp_dir <- tempdir()
      tempImage <- file.path(temp_dir, 'out.png')
      file.copy('out.png', tempImage, overwrite = TRUE)
      png(file, width = 1200, height = 800, units = "px", pointsize = 12, bg = "white", res = NA)
      dev.off()
    })
}

shinyApp(ui = ui, server = server)

Additionally i am not sure how can i choose which of the plotly images should be downloaded. Thanks for any tips and help!

Info:

--> I have tried using webshot, however if I zoom or filter in any way plot, unfortunatelly webshot does not mirror it

--> i am not using the available plotly panel for download, because it is not working using IE

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The OP has edited his/her post to add a requirement:

--> I have tried using webshot, however if I zoom or filter in any way plot, unfortunatelly webshot does not mirror it

Below is a Javascript solution, which doesn't need additional libraries. I'm not fluent in Javascript and I'm not sure the method is the most direct one: I'm under the impression that this method creates a file object from a url and then it creates a url from the file object. I will try to minimize the code.

library(shiny)
library(plotly)

d <- data.frame(X1 = rnorm(50,mean=50,sd=10), 
                X2 = rnorm(50,mean=5,sd=1.5), 
                Y = rnorm(50,mean=200,sd=25))

ui <-fluidPage(
  title = 'Download Plotly',
  sidebarLayout(

    sidebarPanel(
      helpText(),
      actionButton('download', "Download")
    ),

    mainPanel(
      plotlyOutput('regPlot'),
      plotlyOutput('regPlot2'),
      tags$script('
                  function download(url, filename, mimeType){
                    return (fetch(url)
                      .then(function(res){return res.arrayBuffer();})
                      .then(function(buf){return new File([buf], filename, {type:mimeType});})
                    );
                  }
                  document.getElementById("download").onclick = function() {
                  var gd = document.getElementById("regPlot");
                  Plotly.Snapshot.toImage(gd, {format: "png"}).once("success", function(url) {
                    download(url, "plot.png", "image/png")
                      .then(function(file){
                        var a = window.document.createElement("a");
                        a.href = window.URL.createObjectURL(new Blob([file], {type: "image/png"}));
                        a.download = "plot.png";
                        document.body.appendChild(a);
                        a.click();
                        document.body.removeChild(a);                      
                      });
                  });
                  }
                  ')
    )
  )
)

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

  regPlot <- reactive({
    plot_ly(d, x = d$X1, y = d$X2, mode = "markers")
  })
  output$regPlot <- renderPlotly({
    regPlot()
  })

  regPlot2 <- reactive({
    plot_ly(d, x = d$X1, y = d$X2, mode = "markers")
  })
  output$regPlot2 <- renderPlotly({
    regPlot2()
  })

}

shinyApp(ui = ui, server = server)

EDIT

I was right. There's a shorter and cleaner solution:

  tags$script('
              document.getElementById("download").onclick = function() {
              var gd = document.getElementById("regPlot");
              Plotly.Snapshot.toImage(gd, {format: "png"}).once("success", function(url) {
                var a = window.document.createElement("a");
                a.href = url; 
                a.type = "image/png";
                a.download = "plot.png";
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);                      
              });
              }
              ')

EDIT

To select the plot to download, you can do:

  sidebarLayout(

    sidebarPanel(
      helpText(),
      selectInput("selectplot", "Select plot to download", choices=list("plot1","plot2")),
      actionButton('download', "Download")
    ),

    mainPanel(
      plotlyOutput('regPlot'),
      plotlyOutput('regPlot2'),
      tags$script('
                  document.getElementById("download").onclick = function() {
                  var plot = $("#selectplot").val();
                  if(plot == "plot1"){
                    var gd = document.getElementById("regPlot");
                  }else{
                    var gd = document.getElementById("regPlot2");
                  }
                  Plotly.Snapshot.toImage(gd, {format: "png"}).once("success", function(url) {
                    var a = window.document.createElement("a");
                    a.href = url; 
                    a.type = "image/png";
                    a.download = "plot.png";
                    document.body.appendChild(a);
                    a.click();
                    document.body.removeChild(a);                      
                  });
                  }
                  ')
    )
  )

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...