首页 文章

从Shiny(R)下载png

提问于
浏览
13

我对Shiny(和R)很陌生,并且正在努力将我在Shiny制作的情节导出为png文件 .

我看了这两个线程,但无法弄清楚:

Save plots made in a shiny app Shiny downloadHandler doesn't save PNG files

我设法在ui中创建下载按钮,服务器似乎也在做我想做的一切 . 当我点击预览窗口中的下载按钮时,弹出窗口会要求我指定文件位置和名称,但不保存任何文件 . 当我在浏览器窗口中执行相同操作时,会创建一个png文件但它是空的 .

任何见解都非常感谢!

ui.R

library(shiny)

shinyUI(fluidPage(
  titlePanel("This is a scatterplot"),

  sidebarLayout(
    sidebarPanel(

      fileInput('datafile', 'Choose CSV file',
                accept=c('text/csv', 'text/comma-separated-values,text/plain')),

      uiOutput("varselect1"),

      uiOutput("varselect2"),

      downloadButton('downloadPlot', 'Download Plot')

      ),

    mainPanel(          
          h4("Here is your scatterplot"),
          plotOutput("plot1")
                  )
      ))
)

server.R

library(foreign)

shinyServer(function(session,input, output) {

    DataInput <- reactive({
      infile <- input$datafile
      if (is.null(infile)) {

        return(NULL)
      }
      read.csv(infile$datapath)
    })


    output$varselect1 <- renderUI({

      if (identical(DataInput(), '') || identical(DataInput(),data.frame())) return(NULL)

      cols <- names(DataInput())
      selectInput("var1", "Select a variable:",choices=c("---",cols[3:length(cols)]), selected=("---"))

    })

    output$varselect2 <- renderUI({

      if (identical(DataInput(), '') || identical(DataInput(),data.frame())) return(NULL)

      cols <- names(DataInput())
      selectInput("var2", "Select a variable:",choices=c("---",cols[3:length(cols)]), selected=("---"))

    })



    plotInput <- reactive({

      a <- which(names(DataInput())==input$var1)
      x_lab <- as.numeric(DataInput()[,a])


      b <- which(names(DataInput())==input$var2)
      y_lab <- as.numeric(DataInput()[,b])      

      main.text <- paste("Scatterplot of the variables",colnames(DataInput())[a],"and", colnames(DataInput())[b],sep = " ", collapse = NULL)

      plot(x_lab, y_lab, main=main.text, xlab=colnames(DataInput())[a], ylab=colnames(DataInput())[b], xlim=c(min(x_lab),max(x_lab)*1.05), ylim=c(min(y_lab), max(y_lab)*1.05))

      observations <- DataInput()[,1]

      text(x_lab, y_lab, labels=observations, pos=3)


    })

    output$plot1 <- renderPlot({
          print(plotInput())
    })


    output$downloadPlot <- downloadHandler(
      filename = "Shinyplot.png",
      content = function(file) {
        png(file)
        print(plotInput())
        dev.off()
      })    

  })

1 回答

  • 15

    shiny-discuss google group上讨论了这种奇怪场景的解决方法 . 你可以做的只是将你的被动 plotInput 语句改为普通函数 . 不知道为什么 downloadHandler 对反应对象不好玩 .

    # change
    plotInput <- reactive({...})
    
    # into this
    plotInput <- function(){...}
    

    您还可以删除 downloadHandler 调用中的print语句:

    output$downloadPlot <- downloadHandler(
          filename = "Shinyplot.png",
          content = function(file) {
            png(file)
            plotInput()
            dev.off()
          })
    

相关问题