I am trying to create a barplot in R shiny. Data are coming from a csv file and they are filtered according to user's selection in selectInput
and sliderInput
controls.
When the page is loading I am getting the error:
Error in plot.window: need finite 'xlim' values.
Then, when the page is fully loaded, all is fine and working. It looks like the first time app runs, popData which I pass to function barplot is null. I was trying to check if popData is null as advised here before rendering plot but still getting the same error. When I use hard-coded values for selectedCountry and selectedYear instead of reactive expressions, it works okay, I do not get this initial error what makes me think results of selectInput and sliderInput may not available yet when plot is rendered first time(?) How can I fix this? Thanks.
ui <- fluidPage(
titlePanel(title = h3("Population by age")),
sidebarLayout(
sidebarPanel(
uiOutput("geoSelector"),
br(),
uiOutput("yearSlider"),
br()
),
mainPanel(
plotOutput("barChart"),
br()
))
)
server <- function(input, output) {
data <- read.csv("data.csv")
geo = sort(unique(data[,"GeographyName"]))
output$geoSelector <- renderUI({
selectInput("country", "Select country", as.list(geo))
})
minY <- min(unique(data[,"PeriodValue"]))
maxY <- max(unique(data[,"PeriodValue"]))
output$yearSlider <- renderUI({
sliderInput("year", "Select year", min=minY, max=maxY,
value=as.integer(format(Sys.Date(), "%Y")), sep="", animate = TRUE, step=1)
})
selectedCountry <- reactive({input$country})
selectedYear <- reactive({input$year})
selectedData <- reactive({subset(data, GeographyName == selectedCountry() &
PeriodValue == selectedYear())})
selectedDataSorted <- reactive({selectedData()[order(selectedData()$AgeCategoryId),c(1:8)]})
popData <- reactive({selectedDataSorted()$DataPoint})
categ <- reactive({selectedDataSorted()$AgeCategory})
output$barChart <- renderPlot({
barplot(popData(),names.arg=categ(), cex.names = 0.7, border=NA,
xlab="Age Category", ylab="Population (m)")
})
}
shinyApp(ui = ui, server = server)