Search code examples
rshinyshinydashboardshiny-server

How can I make the output's download button behind a "redimensioned" plot?


Good morning,

I am trying to fix the output's download button behind a "redimensioned" plot, but I haven't got the solution so far. Would you have any idea?

Here's a sample code:

ui <- fluidPage(

  titlePanel(
    sidebarLayout(
    sidebarPanel(
      wellPanel(h3("Feed the parameters below"))),

    mainPanel(
      tabsetPanel(
        tabPanel(
          h4("plot"),
          plotOutput(outputId = "plot"),
          downloadButton(outputId = "download_plot", label = "Download plot")))))))


server <- function(input, output){ 

  plot_input <- reactive({ 

      p <- ggplot(data=ChickWeight, aes(x=Time, y=weight, color=Diet, group=Chick)) + geom_line() 

    }) 

  output$plot <- renderPlot({

    print(plot_input())}, width = 1200, height = 800)}

output$download_plot <- downloadHandler(

  filename = function() { paste0("plot_", Sys.Date(), ".png") },

  content = function(file) {

    device <- function(..., width, height) {
      grDevices::png(..., height = 20, res = 300, units = "cm")}

    ggsave(file, plot = plot_input(), device = device)


  })


shinyApp(ui = ui, server = server) 

Solution

  • I am assuming you want that your "Download plot" button to stay on a predetermined place? The most basic solution I could think of is just moving the downloadButton up the main panel like so:

    library(shiny)
    
    ui <- fluidPage(
    
      titlePanel(
        sidebarLayout(
          sidebarPanel(
            wellPanel(h3("Feed the parameters below"))),
    
          mainPanel(
            downloadButton(outputId = "download_plot", label = "Download plot"), #  This 
                                                                                  # is where I moved it to
            tabsetPanel(
    
              tabPanel(
                h4("plot"),
                plotOutput(outputId = "plot")
           # This is where the code-snippet used to be
               ))))))
    
    
    server <- function(input, output){ 
    
      plot_input <- reactive({ 
        df <- ChickWeight
        p <- ggplot(data=df, aes(x=Time, y=weight, color=Diet, group=Chick)) + geom_line() 
    
      }) 
    
      output$plot <- renderPlot({
    
        print(plot_input())}, width = 1200, height = 800)}
    
    output$download_plot <- downloadHandler(
    
      filename = function() { paste0("plot_", Sys.Date(), ".png") },
    
      content = function(file) {
    
        device <- function(..., width, height) {
          grDevices::png(..., height = 20, res = 300, units = "cm")}
    
        ggsave(file, plot = plot_input(), device = device)
    
    
      })
    
    
    shinyApp(ui = ui, server = server) 
    

    Output (Download Button stays over the plot):

    Download Button stays over the plot