Error in downloading plots made within a shiny app

@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"
)