3

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

Stéphane Laurent
  • 75,186
  • 15
  • 119
  • 225
Mal_a
  • 3,670
  • 1
  • 27
  • 60

3 Answers3

2

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);                      
                  });
                  }
                  ')
    )
  )
Stéphane Laurent
  • 75,186
  • 15
  • 119
  • 225
1

1) Install the webshot package.

2) Install phantom.js:

library(webshot)
install_phantomjs()

See ?install_phantomjs for the details.

3) Now you can use the export function of the plotly package:

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(),
      downloadButton('download')
    ),

    mainPanel(
      plotlyOutput('regPlot'),
      plotlyOutput('regPlot2')
    )
  )
)

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()
  })

  output$download <- downloadHandler(
    filename = function(){
      paste0(paste0("test", Sys.Date()), ".png")
    },
    content = function(file) {
      export(regPlot(), file=file)
    })
}

shinyApp(ui = ui, server = server)

You can save to the svg format. See ?export for the explanations.

Stéphane Laurent
  • 75,186
  • 15
  • 119
  • 225
  • Thanks for answer! I am aware of webshot, but the problem with it is that if i zoom into the plot (or in any way filter), it does not apper on the exported png... – Mal_a Nov 15 '18 at 08:57
  • @Mal_a Hmm ok. Why don't you use the *"download plot as png"* button of the plot ? – Stéphane Laurent Nov 15 '18 at 09:00
  • i would actually love to be able to do that! Unfortunatelly at my company our standard web browser is IE, and download plot as png does not work with IE... – Mal_a Nov 15 '18 at 09:01
  • @Mal_a Both simultaneously ? Otherwise, do two download buttons, and copy the code for the other plot. – Stéphane Laurent Nov 15 '18 at 10:34
  • Well i was thinking abpout having some kind of `selectInput("selectplot",...choices="plot1","plot2"...)` and then use its input for choice of which plot should be downloaded, but i guess i can easily then instead of `getElementById("regPlot")`, use `getElementById(input$selectplot)`..i am not very familiar with JavaScript – Mal_a Nov 15 '18 at 10:37
0

Instead of using webshot, you should consider to try webshot2. See my detailed answer to the similar case.

# Webshot and phantomjs have been previously installed.
library(webshot2)
ozturkib
  • 1,493
  • 16
  • 28
  • I have prepared a blog post including various details about webshot2. You can see the details from http://www.ozturkibrahim.com/export-save-r-graphs-with-webshot/ – ozturkib Apr 28 '20 at 15:34