Sukhi
Sukhi

Reputation: 846

using downloadHandler and renderPlot on a static function simultaneously

Please consider the following:

# createPlot takes in data, processes it and generates a plot using native plot()
    plotInput <- function(){       
     createPlot(data=data(),name=input$name)
    }

# I render it using
output$plot <- renderPlot({
    plotInput()
  }, height=700,width=850,res=100)

# and I download the pdf using
output$pdflink <- downloadHandler(
      filename <- "plot.pdf",
      content <- function(file){
        pdf("plot.pdf")
        print(plotInput())
        dev.off()
        file.copy("plot.pdf", file)
      }
  )

createPlot function has a randomising factor which fills in the empty values with a small random pseudocount. So, whenever this function is run, the points on the plot are not exactly the same thus the downloaded plot is a bit different than what I see on the interface. What can I do to come around this problem?

I've tried storing the output of plotInput() to a static variable and re-sue that variable for both rendering and exporting but it doesn't works like this.

mainPlot <- plotInput()

Upvotes: 0

Views: 351

Answers (2)

Sukhi
Sukhi

Reputation: 846

I solved it by generating a static pdf plot which I converted to a .png using ImageMagick and the rendered the converted image to the browser using the renderImage

# createPlot takes in data, processes it and generates a plot using native plot()
    plotInput <- reactive({       
     createPlot(data=data(),name=input$name)
    })

# I render it using
    output$plot <- renderImage({
     pdf("plot.pdf")
     print(plotInput())
     dev.off
# R wrapper for imagemagick
   im.convert('plot.pdf',output='plot.png',extra.opts="-density 250 -quality 100")
    list(src='plot.png',
     contentType='image/png',
     alt='emptyPlot')
   },deleteFile=FALSE)

# and I download the pdf using
    output$pdflink <- downloadHandler(
      filename <- "plot.pdf",
      content <- function(file){
        file.copy("plot.pdf", file)
      }
    )

Upvotes: 0

CPhil
CPhil

Reputation: 927

Instead of making plotInput a function, try making it into a "reactive". Shiny should detect that when printing to file, there is no need to rerun the reactive if none of its inputs have changed, and therefore the renderPlot and the pdf should use the same plot

Upvotes: 1

Related Questions