Custom renderPlot to pdf

Hi, I would like to send a custom plot (not using ggplot2) to a pdf file but cannot work out how to get the contents of renderPlot to the pdf. Below is an example of what I am trying to do. Any ideas on how to do this?
Thanks!

library(shiny)
library(grid)
library(gridExtra)
library(devtools)

ui <- fluidPage(
titlePanel("Old Faithful Geyser Data"),

sidebarLayout(
    sidebarPanel(
        sliderInput("bins",
                    "Number of bins:",
                    min = 1,
                    max = 30,
                    value = 10)
    ),

    mainPanel(
        textOutput("plotTitle"),
       plotOutput("distPlot")
    )
), 
downloadButton('export', "Download pdf")

)

server <- function(input, output) {

plotFunc<-reactive({
    x    <- faithful[, 2]
    bins <- seq(min(x), max(x), length.out = input$bins + 1)
    
    hist(x, breaks = bins, col = 'darkgray', border = 'white')
})

text1<-reactive({
    (paste("The user selected ", input$bins)  )
})

output$plotTitle <- renderText({
    text1()
})

output$distPlot <- renderPlot({
    plotFunc()
})

plotPDF<-reactive({
    grid.grabExpr(print((plotFunc())))
})

output$export = downloadHandler(
    filename = function() {"Plot output.pdf"},
    content = function(file) {
        pdf(file, paper = "default")
        grid.text("This is some initial text",  x=0.5, y=.9, gp=gpar(fontsize=18), check=TRUE)
        grid::grid.newpage()
        grid.text(text1())
        grid.arrange(plotPDF()) #I get stuck here#
        grid::grid.newpage()
        grid.text("This is some final text",  x=0.5, y=.9, gp=gpar(fontsize=18), check=TRUE)
        dev.off()
    }
) 

}

shinyApp(ui = ui, server = server)

Hi,

Welcome to the RStudio community!

You need to explicitly call the plot() function if you want to save an image. That's all you need to do:

output$export = downloadHandler(
    filename = function() {"Plot output.pdf"},
    content = function(file) {
        pdf(file, paper = "default")
        grid.text("This is some initial text",  x=0.5, y=.9, gp=gpar(fontsize=18), check=TRUE)
        grid::grid.newpage()
        grid.text(text1())

        plot(plotFunc()) #this is all you need

        grid::grid.newpage()
        grid.text("This is some final text",  x=0.5, y=.9, gp=gpar(fontsize=18), check=TRUE)
        dev.off()
    }
) 

Hope this helps,
PJ

This topic was automatically closed 54 days after the last reply. New replies are no longer allowed.

Hi,

You just use whatever plotting function is used to normally plot the image/graph. Could you give an example?

PJ

Thanks, that is helpful. Is there is a similar function to plot() that can be used if plotFunc() renders an image instead of a plot?