Black Lives Matter. Please consider donating to Black Girls Code today.
Learn how to use COVID-19 data in open source Dash apps. Register for the Sept 23rd webinar with IQT!

Save custom ggplotly plot to pdf (in Shiny)

I would like to export ggplotly plot in Shiny in a format of PDF. I can do it with plotly::exportand shiny::downloadHandler function but I have an extra need: I would like to save that kind of ggplotly plot which the user can customize inside the app (for example zooming on it or filter some of the elements, etc.).

Here is an example:

library(webshot)
library(htmlwidgets)
library(raster)
library(ggplot2)
library(shiny)
library(plotly)

server <- function(input, output, session) {

#PLOT FUNCTION
target_plot <- reactive({
dsamp <- diamonds[sample(nrow(diamonds), 1000), ]
p <- qplot(carat, price, data=dsamp, colour=clarity)

  ggplotly(p)
})

output$plot_display <- renderPlotly({
target_plot()
})

#EXPORT FUNCTION
output$plot_export <- downloadHandler(“test.pdf”, function(theFile) {

  makePdf <- function(filename){
    pdf(file = filename)
    
    export(target_plot(), file = "test.png")
    
    r <- brick(file.path(getwd(), "test.png"))
    plotRGB(r)
    
    dev.off()
  }
  
  makePdf(theFile)
})

}

user interface

ui <- fluidPage(

sidebarLayout(

sidebarPanel(
  downloadButton("plot_export", label = "download")
),

mainPanel(
  plotlyOutput("plot_display", height = "550px")
)

)
)

shinyApp(ui = ui, server = server)

Unfortunately this solution always produces the same pdf file. It does not care about the possible user modifications in the Shiny app. For example if I hide all of the elements except the “VVS1” the export remains the same.

I know there is an easy bulit in function (in the Modebar) in Plotly to export plots but I need a solution which works also in the R pdf() function, because I would like to create a report with many different plots.