R Shiny : read data file, 让用户选择变量,用 ggplot 作图

标签 r ggplot2 shiny

如标题所述,我正在尝试使用 R 中的 Shiny 创建一个程序来读取用户上传的 csv 文件,之后用户可以从该文件中选择一个变量来查看绘制的图通过 ggplot。我试图通过两个选项卡实现这一点,第一个选项卡将读取文件,第二个选项卡将让用户选择变量以查看绘图。

我的代码如下。目前,我能够成功读取用户文件,但无法根据所选变量进行绘图(我目前只有 1 个变量“Location”用于演示)。 (HomeWTaxAmt 是要绘制的 y 变量)。

library(shiny)
library(ggplot2)
library(data.table)
library(RColorBrewer)
options(scipen=1000)

ui <- fluidPage(
  navbarPage("User Interface:",tabPanel("Upload",
  titlePanel("Uploading Files"),
  sidebarLayout(
    sidebarPanel(
      fileInput("file1", "Choose CSV File",
                multiple = TRUE,
                accept = c("text/csv",
                           "text/comma-separated-values,text/plain",
                           ".csv")),
      tags$hr(),
      checkboxInput("header", "Header", TRUE),
      radioButtons("sep", "Separator",
                   choices = c(Comma = ",",
                               Semicolon = ";",
                               Tab = "\t"),
                   selected = ","),
      tags$hr(),
      radioButtons("disp", "Display",
                   choices = c(Head = "head",
                               All = "all"),
                   selected = "head"),
      radioButtons("quote", "Quote",
                   choices = c(None = "",
                               "Double Quote" = '"',
                               "Single Quote" = "'"),
                   selected = '"')),
    mainPanel(
      verbatimTextOutput("summary"),
      tableOutput("contents")
    ))), 
  tabPanel("Graphing",
                 titlePanel("Plotting Graphs"),
                 sidebarLayout(
                   sidebarPanel(
                     selectInput("variable", "Variable:",
                                 list("Location"))),
                   mainPanel(
                     h3(textOutput("caption")),
                     plotOutput("ggplot")
                   )
  ))
))

server <- function(input, output) {
  output$contents <- renderTable({
    req(input$file1)
    library(data.table)
    data <- fread(input$file1$datapath,
                  header = input$header,
                  sep = input$sep,
                  quote = input$quote)

    if(input$disp == "head") {
      return(head(data))
    }
    else {
      return(data)
    }

  })
  output$summary <- renderPrint({
    summary(data)
  })

  formulaText <- reactive(function() {
    paste("HomeWTaxAmt ~", input$variable)
  })

  output$caption <- renderText(function() {
    formulaText()
  })

  output$ggplot <- renderPlot(function() {
    data <- fread(input$file1$datapath,
                  header = input$header,
                  sep = input$sep,
                  quote = input$quote)
    if(is.null(data)) return(NULL)
    # check for the input variable
    ggplot(data, aes(x=reorder(factor(data[input$variable]), -abs(HomeWTaxAmt), function(x){sum(x)}), 
                     weight = abs(HomeWTaxAmt), fill = factor(data[input$variable]))) + geom_bar(show.legend=FALSE) + xlab(input$variable) + 
            scale_fill_manual(values=brewer.pal(n = 12, name = "Paired"))
  })
}

shinyApp(ui, server)

最佳答案

由于我无法访问您的确切 .csv 文件,我不得不对绘图命令进行一些调整,但我很确定您可以从那里开始并让它与您的数据一起使用。请注意,现在不加载 .csv 文件会在第一个选项卡上显示错误,这些错误会在数据加载后立即消失。您可能希望在此处使用一些 ifelse 开关来确保最终用户不必看到这些 R 错误。

这是根据我拥有的一些示例数据按预期绘制绘图的代码:

library(shiny)
library(ggplot2)
library(data.table)
library(RColorBrewer)
options(scipen=1000)

#XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
# I didn't change anything in this section
ui <- fluidPage(
  navbarPage("User Interface:",tabPanel("Upload",
                                        titlePanel("Uploading Files"),
                                        sidebarLayout(
                                          sidebarPanel(
                                            fileInput("file1", "Choose CSV File",
                                                      multiple = TRUE,
                                                      accept = c("text/csv",
                                                                 "text/comma-separated-values,text/plain",
                                                                 ".csv")),
                                            tags$hr(),
                                            checkboxInput("header", "Header", TRUE),
                                            radioButtons("sep", "Separator",
                                                         choices = c(Comma = ",",
                                                                     Semicolon = ";",
                                                                     Tab = "\t"),
                                                         selected = ","),
                                            tags$hr(),
                                            radioButtons("disp", "Display",
                                                         choices = c(Head = "head",
                                                                     All = "all"),
                                                         selected = "head"),
                                            radioButtons("quote", "Quote",
                                                         choices = c(None = "",
                                                                     "Double Quote" = '"',
                                                                     "Single Quote" = "'"),
                                                         selected = '"')),
                                          mainPanel(
                                            verbatimTextOutput("summary"),
                                            tableOutput("contents")
                                          ))), 
             tabPanel("Graphing",
                      titlePanel("Plotting Graphs"),
                      sidebarLayout(
                        sidebarPanel(
                          selectInput("variable", "Variable:",
                                      list("Location"))),
                        mainPanel(
                          h3(textOutput("caption")),
                          plotOutput("ggplot")
                        )
                      ))
  ))
#XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX


server <- function(input, output, session) {  # make sure to include "session" here, in order to update your inputs later
  # create an reactive upload to access your data more quickly and easily
  reactive_data <- reactive({
    print(input$file1$datapath)
    data <- fread(input$file1$datapath,
                  header = input$header,
                  sep = input$sep,
                  quote = input$quote)
    return(data)
  })

  # preview
  # no library(data.table) required here, as its already loaded at the beginning of the script)
  output$contents <- renderTable({
    # load your data
    data <- reactive_data()

    if(input$disp == "head") {
      return(head(data))
    }
    else {
      return(data)
    }

  })
  output$summary <- renderPrint({
    summary(reactive_data())
  })

  formulaText <- reactive({ # no need for function() here
    paste("HomeWTaxAmt ~", input$variable)
  })

  output$caption <- renderText({
    formulaText()
  })

  output$ggplot <- renderPlot({

    # load your data
    data <- reactive_data()

    # to only plot when data is not NULL, make sure to include the plotting command in the if-else statement
    # no data
    if(is.null(data)){
      return(NULL)

    }else{
    # data

      # update your selectInput first, so that all the variables match your .csv headers
      updateSelectInput(session, "variable",
                        choices = colnames(data),
                        selected = input$variable) # this keeps the input on the last thing selected on tab-change

      # check for the input variable
      # I used aes_string here so that indexing the colnames works
      # you'll have to adjust the plotting command to your needs as my .csv files aren't the same as yours
      plot <- ggplot(data, aes_string(x=colnames(data)[colnames(data) == input$variable], colnames(data)[length(colnames(data))]))+
        geom_bar(stat="identity")

      # Display your plot
      print(plot)

    }

  })
}

shinyApp(ui, server)

关于R Shiny : read data file, 让用户选择变量,用 ggplot 作图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53113065/

相关文章:

r - qplot ylab 中的下标和上标 [R]

r - 如何使用 R 将本地 png 文件复制粘贴到 Word 文档?

r - 在 R 中创建到 DBMS 的连接

r - R 中表格的条件格式......更好的方法?

r - 在每个方面更改选项

r - R : Reactive Values vs. 全局变量中的 Shiny

在 R 中读取 SDMX - 解析错误?

r - Geom_tile 绘制时间轴数据中不存在的不连续性

r - 我的 r Shiny 应用程序需要 dockerfile 中的 odbc 驱动程序

r - 如何在安装了防火墙的情况下连接到shinyapps?