add 'copy plot to clipboard' button to shiny app with ggplot

Hi all. I posted this on stackoverflow, but it really is shinyapps specific, so I figured I's post it here.
I'm wondering if it's possible to add a simple button in Shiny that copies a plot (ggplot specifically) to the user's clipboard.

Below the code I have so far. When I run the app locally in Windows with R studio, the plot DOES actually copy to my clipboard. However, clicking the button first pops up a new window with just the plot in it, but the plot itself IS copied to my clipboard. The issue is when I deploy this to my shinyappsio server, the button does not work - instead it just crashes the app (see error log below).

The things I'd like to accomplish:

  1. Copy the plot to clipboard in shinyappsio environment
  2. NOT have a window pop up that first shows the plot
  3. Ideally, I'd like to specify the width and height of the plot being copied.

My current code:

library(ggplot2)
library(shiny)

d <- data.frame(xaxis = c(1,2,3,4,5), 
                ydata = sample(1:500, 5))

p <- ggplot(data = d, aes(x = xaxis, y = ydata)) +
  geom_line()



ui <- fluidPage(
  fluidRow(
      plotOutput(outputId = "myplot"),
      actionButton(inputId = "copyme", label = "Copy plot to clipboard")
  )
)

server <- function(input, output) {
  output$myplot <- renderPlot({
    p
  })
  
  observeEvent(input$copyme, {
    dev.new()
    print(p)
    savePlot("clipboard")
    print("copied")
  })
}

shinyApp(ui, server)

Error log from shinyappsio:

2020-11-10T16:01:33.648258+00:00 shinyapps[3203167]: Listening on http://127.0.0.1:44881
2020-11-10T16:01:52.749743+00:00 shinyapps[3203167]: Warning: Error in savePlot: can only copy from 'X11(type="*cairo")' devices
2020-11-10T16:01:52.754119+00:00 shinyapps[3203167]:   86: stop
2020-11-10T16:01:52.754120+00:00 shinyapps[3203167]:   85: savePlot
2020-11-10T16:01:52.754121+00:00 shinyapps[3203167]:   84: observeEventHandler [/srv/connect/apps/jrdev/app.R#28]
2020-11-10T16:01:52.754122+00:00 shinyapps[3203167]:   13: runApp
2020-11-10T16:01:52.754122+00:00 shinyapps[3203167]:   12: fn
2020-11-10T16:01:52.754123+00:00 shinyapps[3203167]:    7: connect$retry
2020-11-10T16:01:52.754123+00:00 shinyapps[3203167]:    6: eval
2020-11-10T16:01:52.754123+00:00 shinyapps[3203167]:    5: eval

:link: Always link to your other posts, and update everywhere with any solutions

(FAQ: Is it OK if I cross-post?)

1 Like

shinyapps.io in principle can't change the copy and paste buffers of client devices.
I expect the solution will involve something like writing out the plot to a temporary image file, and then using some javascript to facilitate copy and pasting, but that's easier said than done, at least for me as I know R a lot better than I know javascript...

1 Like