阅读 excel 个文件后使用闪亮的应用程序下载 pdf 绘图

Downloading pdf plot using shiny app after reading excel files

因为,我是 shiny 应用程序的新手,需要一些帮助,上传 excel 文件并在 shiny 应用程序中生成 table 输出工作正常,但无法将情节下载为 pdf格式 这是我的代码

library(shiny)
library(openxlsx)
library(lattice)

runApp(
  list(
    ui = fluidPage(
      titlePanel("plots"),
      sidebarLayout(
        sidebarPanel(
          fileInput('file1', 'Choose xlsx file',
                    accept = c(".xlsx")),
          tags$hr(),
          downloadButton('down',"download plot")
        ),
        mainPanel(
          tableOutput('contents'),
        plotOutput('plot'))
      )
    ),
    server = function(input, output){
      output$contents <- renderTable({
        inFile <- input$file1

        if(is.null(inFile))
          return(NULL)
        else
        read.xlsx(inFile$datapath)
      })

      plotInput <- reactive({
        df <- input$file1
        xyplot(df[,2]~df[,1],df(),xlim=c(0,10),ylim=c(0,100),type = "b")
      })

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

      output$down <- downloadHandler(
        filename = function(){paste("plot",".pdf",sep=".") },
        content = function(file) {
          pdf(file)
         xyplot(df[,2]~df[,1],df(),xlim=c(0,10),ylim=c(0,100),type = "b")
          dev.off()
        }
      )
    }
  )
)

问题在于,在您的代码的某些部分,您通过 df() 访问动态数据框,但您从未定义它。

在这种问题中,最好创建一个响应式数据框,比如 df,其中包含上传的数据,并通过 df() 传递给代码的其他响应式部分。


完整示例:

library(shiny)
library(openxlsx)
library(lattice)

runApp(
  list(
    ui = fluidPage(
      titlePanel("plots"),
      sidebarLayout(
        sidebarPanel(
          fileInput('file1', 'Choose xlsx file',
                    accept = c(".xlsx")),
          tags$hr(),
          downloadButton('down',"download plot")
        ),
        mainPanel(
          tableOutput('contents'),
          plotOutput('plot'))
      )
    ),
    server = function(input, output){


      df <- reactive({
        inFile <- input$file1
        req(inFile) # require that inFile is available (is not NULL) 
                    # (a user has uploaded data)

        # read.xlsx(inFile$datapath)
        head(iris, 10)
      })

      output$contents <- renderTable({
        # access uploaded data via df()
        df()
      })

      plotInput <- reactive({
        df <- df()
        xyplot(df[,2]~df[,1], df ,xlim=c(0,10),ylim=c(0,100),type = "b")
      })

      output$plot <- renderPlot({
        plotInput()
      })

      output$down <- downloadHandler(
        filename = function(){paste("plot",".pdf",sep=".") },
        content = function(file) {
          pdf(file)
          #xyplot(df[,2]~df[,1],df(),xlim=c(0,10),ylim=c(0,100),type = "b")

          # you have to print the plot so that you can open pdf file
          print(plotInput())
          dev.off()
        }
      )
    }
  )
)