用闪亮的r创建一个条形图

时间:2017-07-21 17:38:27

标签: r csv shiny

我是R的新手,正在寻求帮助。我有两行(2000年,2010年)和两列(人口997936家庭391043 2000和2010 1229226和474030)的csv。我正在尝试创建一个响应条形图,使用闪亮的单选按钮来选择2000或2010数据,但无法使其工作。我知道它与我过滤的方式有关,但我无法弄明白。这是我的代码,我真诚地感谢任何帮助。正如你在评论中所看到的那样,我一直在尝试很多。

library(shiny)

data <- read.csv("hillsctypop.csv", header = TRUE, sep = ",", stringsAsFactors = FALSE)

ui <- fluidPage(
  titlePanel(title = h4("Hillsborough County Population by Census", align="center")),
  sidebarPanel(

    radioButtons("YEAR", "Select the Census Year",
                 choices = c("2000", "2010"),
                 selected = "2000")),


  mainPanel(
    plotOutput("bar",height = 500))
)

server <- function(input,output){
  #year = reactive(data({input$YEAR}))
  # filtered <- reactive({
  #data %>%
  #filter(Type == input$year)
  #})
  output$bar <- renderPlot({
   #  barplot(as.matrix(data))
   # barplot(data()[,2,4,])
   #x <- data[1, ]
    color <- c("blue", "red")

    barplot(as.integer(data$Population, data$Households),
            main = input$YEAR,
            ylab="Total",
            xlab="Census Year",
            names.arg = c("Population", "Households"),
            col = color)
    #legend("topright", legend = c("Population", "Households"),
    #      fill = c("Blue", "red"))
  })
}
shinyApp(ui=ui, server=server)

1 个答案:

答案 0 :(得分:1)

这对我有用。请注意,我已将数据更改为我自己的样本数据,并且我假设有一个列'年'表示数据属于2000年或2010年。随后将被动用作绘图功能的输入。我希望这有助于指出你正确的方向。

data = data.frame(Population=sample(1:20,10),Households = sample(1:20,10), year=sample(c(2000,2010),10,replace=T))

ui <- fluidPage(
  titlePanel(title = h4("Hillsborough County Population by Census", align="center")),
  sidebarPanel(

    radioButtons("YEAR", "Select the Census Year",
                 choices = c("2000", "2010"),
                 selected = "2000")),


  mainPanel(
    plotOutput("bar",height = 500))
)

server <- function(input,output){

  reactive_data = reactive({
    selected_year = as.numeric(input$YEAR)
    return(data[data$year==selected_year,])

  })

  output$bar <- renderPlot({

    color <- c("blue", "red")

    our_data <- reactive_data()

    barplot(colSums(our_data[,c("Population","Households")]),
            ylab="Total",
            xlab="Census Year",
            names.arg = c("Population", "Households"),
            col = color)
  })
}
shinyApp(ui=ui, server=server)