plotly.R icon indicating copy to clipboard operation
plotly.R copied to clipboard

Download images in Shiny

Open limbo1996 opened this issue 3 years ago • 1 comments

Hi! I'm using plotly in a shiny. When I want to download the image, first I used export, it works, but it returns a message "use orca", but it was also superseded by kaleido(). So I use save_image(), and it return an error .

Warning: Error in py_run_string_impl:   File "<string>", line 1
    open('C:\Users\limbo\AppData\Local\Temp\RtmpkD8Zlu\file1d5837d66529.png', 'wb').write(scope_1d58780818d2.transform(sys.modules['json'].loads(scope_1d58780818d2._last_plot), format='png', width=None, height=None, scale=None))
                                                                            ^
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape

  [No stack trace available]

my shiny

library(shiny)
library(plotly)

ui <- fluidPage(
  plotlyOutput("plot"),
  downloadButton("download", "Download")
)

server <- function(input, output, session) {
  p <- reactive({
    
    a <- ggplot(iris, 
                aes(x = Species, 
                    y = Sepal.Length)
                ) + 
      geom_boxplot() + 
      theme_bw()
    a <- ggplotly(a)
    a
  })

  
  output$plot <- renderPlotly(p())
  
  output$download <- downloadHandler(
    filename = function(){
      paste0(paste0("test", 
                    Sys.Date()), 
             ".png")
    },
    
    content = function(file){
      plotly::save_image(p(), file = file)
    }
  )
}

shinyApp(ui, server)

What can I do about that? Thanks!

limbo1996 avatar Jun 09 '22 09:06 limbo1996

The error is caused by the default file path string in R uses "\\" as delimiter and the save_image in python is not able to understand it.

Just add in a function to replace "\\" to "/" on the file before passing it into save_image then you are good to go.

Modification on your code block here:

content = function(file){ file <- str_replace_all(file, pattern="\\\\", replacement="\/") plotly::save_image(p(), file = file) }

badcookie78 avatar Jul 25 '22 06:07 badcookie78