如何在Shiny中将fileInput连接到ggplot?

时间:2017-09-28 07:25:07

标签: r rstudio shiny

我今天已经在这方面工作了6个多小时,我知道这是一个简单的问题,但我无法理解。我想要的是输入一个文件,然后能够使用多个selectInput下拉菜单来更改ggplot上的输出。以下是我到目前为止的情况:

UI:

ui = dashboardPage(
  dashboardHeader(title = "Apple Financials"),
  dashboardSidebar(
    fileInput("file1", label = "Upload SAS Data:", accept = ".sas7bdat"),
    selectInput("x", label = "X-Axis Variable", choices = c("Sales", "Cash", "Assets", "Profits", "R&D", "SG&A")),
    selectInput("y", label = "Y-Axis Variable", choices = c("Sales", "Cash", "Assets", "Profits", "R&D", "SG&A"), selected = "R&D"),
    selectInput("scale", label = "Choose the Scale:", choices = c("Levels", "Log 10")),
    radioButtons("model", label = "Choose the Model:", choices = c("Linear Model", "LOESS", "Robust Linear", "None"), selected = "LOESS"),
    checkboxInput("ribbon", label = "Standard Error Ribbon", value = TRUE),
    conditionalPanel(
      condition = "input.model == 'LOESS'",
      sliderInput("span", label = "Span for LOESS", min = 0, max = 1, value = .75)
    )
  ),
  dashboardBody(
    box(width = NULL, height = 415, plotOutput("plots"))
  )
)

服务器:

server = function(input, output) {


   observe({
     data = input$file1
      if(is.null(data))
      return(NULL)

    df = read_sas(data$datapath)
    output$plots = renderPlot({
    ggplot(df, aes(x = input$x, y = input$y)) +
      geom_line()
   })
 })
}

1 个答案:

答案 0 :(得分:2)

由于输入是字符串,我们需要aes_string

中的ggplot
server = function(input, output) {


  observe({
    data = input$file1
    if(is.null(data))
      return(NULL)

    df = read_sas(data$datapath)
    output$plots = renderPlot({
      ggplot(df, aes_string(x = input$x, y = input$y)) +
        geom_line()
    })
  })
}
shinyApp(ui, server)

enter image description here

注意:为了演示,我们正在上传csv文件而不是SAS文件