Error in downloading plots made within a shiny app

Hi,
I want to download the following plot from my shiny app as either pdf or png but it's not working. can I get the correct code to download it?

R_code <-   output$plot2 <- renderPlot({
    pca_output <- pca_objects()$pca_output
    eig = (pca_output$sdev)^2
    variance <- eig*100/sum(eig)
    cumvar <- paste(round(cumsum(variance),1), "%")
    eig_df <- data.frame(eig = eig,
                         PCs = colnames(pca_output$x),
                         cumvar =  cumvar)
    ggplot(eig_df, aes(reorder(PCs, -eig), eig)) +
      geom_bar(stat = "identity", fill = "white", colour = "black") +
      geom_text(label = cumvar, size = 4,
                vjust=-0.4) +
      theme_bw(base_size = 14) +
      xlab("PC") +
      ylab("Variances") +
      ylim(0,(max(eig_df$eig) * 1.1))
  })

@Sara01 Welcome to Community!

Check out Using downloadHandler and R Studio 'Export as pdf' (cairo_pdf) for a working example . This is example is using base plot and not ggplot2.

Given ggplot2 plot objects can be saved, I would update the code to do something like:

plot_obj <- reactive({
    pca_output <- pca_objects()$pca_output
    eig = (pca_output$sdev)^2
    variance <- eig*100/sum(eig)
    cumvar <- paste(round(cumsum(variance),1), "%")
    eig_df <- data.frame(eig = eig,
                         PCs = colnames(pca_output$x),
                         cumvar =  cumvar)
    ggplot(eig_df, aes(reorder(PCs, -eig), eig)) +
      geom_bar(stat = "identity", fill = "white", colour = "black") +
      geom_text(label = cumvar, size = 4,
                vjust=-0.4) +
      theme_bw(base_size = 14) +
      xlab("PC") +
      ylab("Variances") +
      ylim(0,(max(eig_df$eig) * 1.1))
})

output$plot2 <- renderPlot({
  plot_obj()
})

output$downloadPdf <- downloadHandler(
  filename = function(){paste(input$dataset, '.pdf', sep = '')},
  content = function(file){
    ggsave(file, plot_obj())
  },
  contentType = "application/pdf"
)

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