javascript - 使用 javascript 时从 Shiny 的应用程序下载绘图时出错

标签 javascript r download shiny plotly

我下面有一个 Shiny 的应用程序,它显示绘图或表格。我对表格不感兴趣,我的问题只涉及 plotly 部分。当我使用此 javascript solution 在浏览器中打开应用程序时,我尝试下载该图。 。我不熟悉 javascript,我想知道当我第一次按下“下载”按钮并只下载我根本没有下载的图时,如何防止它下载这个空文件。

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'),
      tags$script('
              document.getElementById("down").onclick = function() {
                  var gd = document.getElementById("regPlot");
                  Plotly.Snapshot.toImage(gd, {format: "png"}).once("success", function(url) {
                  var a = window.document.createElement("a");
                  a.href = url; 
                  a.type = "image/png";
                  a.download = "plot.png";
                  document.body.appendChild(a);
                  a.click();
                  document.body.removeChild(a);                      
                  });
                  }
                  ')
    ),

    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(){
        paste(paste("test",Sys.Date(),sep=""), ".png",sep="")},
      content = function(file) {
        temp_dir <- tempdir()
        tempImage <- file.path(temp_dir, 'out.png')
        file.copy('out.png', tempImage, overwrite = TRUE)
        png(file, width = 1200, height = 800, units = "px", pointsize = 12, bg = "white", res = NA)
        dev.off()
      })
    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)

最佳答案

这是下载 plotly 的代码。代码中很少有问题,

在 ui.R 中定义下载按钮。并引用javascript代码中的下载按钮id。此外,regplotuiOutput 元素,而不是实际的绘图。在 JavaScript 代码中,该图由 pl 引用。

以下是已修复问题的示例代码。如果您使用的是 javascript 代码,则不需要 Shiny 的下载处理程序。如下所示,您可以简单地从操作按钮下载。

您可以在此基础上通过将 actionButton 替换为 downloadButton 并在服务器上添加相应的代码来下载数据表。

library(shiny)
library(plotly)
library(DT)

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

    sidebarPanel(
      selectInput("S","SELECT",choices = c("Table","Plot"),selected = "Plot"),
      actionButton("downloadData", "Download",class = "butt1"),
      tags$script('
                  document.getElementById("downloadData").onclick = function() {
                  var gd = document.getElementById("pl");
                  Plotly.Snapshot.toImage(gd, {format: "png"}).once("success", function(url) {
                  var a = window.document.createElement("a");
                  a.href = url; 
                  a.type = "image/png";
                  a.download = "plot.png";
                  document.body.appendChild(a);
                  a.click();
                  document.body.removeChild(a);                      
                  });
                  }
                  ')
      ),

    mainPanel(
      uiOutput('regPlot')

    )
      )
    )

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

  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))

  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)

关于javascript - 使用 javascript 时从 Shiny 的应用程序下载绘图时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54593775/

相关文章:

javascript - 带有 Google 日历日期的 Json 字符串

javascript - 当在对象中找不到键时返回不同的值而不是未定义

javascript - 为什么 1 ["foo"] 返回未定义而不是错误?

r - 花呢的有限混合

vb.net - 使用 FTP 下载每个文件 *WHILE* 获取文件列表

JavaScript:任何人都可以让它工作或解释为什么它不起作用吗?

R raster::calc 计算分位数 na.rm = FALSE

r - 将函数应用于数据框中的分组行

php - 使用 PHP 和 JavaScript 下载状态

file - 如何从 iCloud.com 下载文件夹