使用动态 downloadHandler() 从闪亮的应用程序下载动态绘图图动态、应用程序、downloadHandler

2023-09-06 07:39:36 作者:半盏清茶丶

我有下面闪亮的应用程序,我试图通过 downloadHandler() 从中下载绘图图.问题是我试图下载的对象是数据表或绘图,所以我不知道如何将它传递给 downloadHandler().请注意,我的下载按钮也是动态的,因为在第一种情况下它应该下载一个表格,而在第二种情况下应该下载一个绘图.请注意,我只关心这里的情节.在浏览器中打开应用程序.首先我安装:

I have the shiny app below from which Im trying to download the plotly graph through downloadHandler(). The issue is that the object that Im trying to download is either a datatable or a plotly plot so I do not know how to pass it to the downloadHandler(). Note that my download button is dynamic as well because in the first case it should download a table and in the second a plot. Note that I care just for the plot here.Open the app in browser.Firstly I install:

library(webshot)
install_phantomjs()

然后:

    library(shiny)
library(plotly)

d <- data.frame(X1 = rnorm(50,mean=50,sd=10), 
                X2 = rnorm(50,mean=5,sd=1.5), 
                Y = rnorm(50,mean=200,sd=25))

ui <-fluidPage(
  title = 'Download Plotly',
  sidebarLayout(

    sidebarPanel(
      selectInput("S","SELECT",choices = c("Table","Plot"),selected = "Plot"),
      uiOutput('down')
    ),

    mainPanel(
      uiOutput('regPlot')

    )
  )
)

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

output$down<-renderUI({
  if(input$S=="Table"){

      output$downloadData <- downloadHandler(
        filename = function() {
          paste(input$filename, input$extension, sep = ".")
        },

        # This function writes data to a file given to it by the argument 'file'.
        content = function(file) {
          sep <- "txt"=","
          # Write to a file specified by the 'file' argument
          write.table(data.frame(mtcars), file, sep = sep,
                      row.names = FALSE)
        }

      )
      downloadButton("downloadData", "Download",class = "butt1")
  }
  else{
    output$downloadData <- downloadHandler(
      filename = function(){
        paste0(paste0("test", Sys.Date()), ".png")
      },
      content = function(file) {
        export(regPlot, file=file)
      }) 
    downloadButton("downloadData", "Download",class = "butt1")
  }
})  

output$regPlot<-renderUI({
  if(input$S=="Plot"){
    output$pl<-renderPlotly(
    plot_ly(d, x = d$X1, y = d$X2, mode = "markers"))
    plotlyOutput("pl")
  }
  else{
    output$tbl =  DT::renderDataTable(datatable(
      d
    ))
    dataTableOutput("tbl") 
  }
  })

}

shinyApp(ui = ui, server = server)

推荐答案

根据情节网站使用以下代码:

if (!require("processx")) install.packages("processx")

p <- plot_ly(z = ~volcano) %>% add_surface()

orca(p, "surface-plot.png")
 
精彩推荐
图片推荐