Student Details

Story URL

Data Source

Visualisation URL

Code

library(shiny)
library(ggplot2)
library(tidyr)
library(readxl)

#Read the data
alcohol_raw <- read_excel("Alcohol Consumption.xls", col_names = FALSE, sheet = 8)

alcohol <- alcohol_raw[, -c(2:6)]

#Renaming columns
colnames(alcohol) <- c("Year", "Beer", "Wine", "Spirits", "Cider", "Total")

#Reshaping columns from wide to long format
alcohol2 <- alcohol %>% gather(key = 'Alcohol', value = 'Volume', -Year)

#Reordering factors in Alcohol column
alcohol2$Alcohol <- factor(alcohol2$Alcohol, levels = c("Beer", "Cider", "Spirits", "Wine", "Total"), ordered = TRUE)

# Define UI for application that draws a histogram
ui <- fluidPage(
  #Title of visualisation
  titlePanel("Alcohol Consumption Across Australia per Person"),
  sidebarLayout(
    sidebarPanel(
      #Slider input
      sliderInput("Year", "Year",
                  min(alcohol2$Year), max(alcohol2$Year),
                  value = 2000, animate = animationOptions(interval = 500, loop = TRUE)),
      #Assistive text for interactive tool
      strong("Please select a year to view alcohol consumption for a specific period or press play to view the                      changes across time."),
      br(),
      br(),
      p("Note that there is no recorded cider consumption until 2005."), 
      p("In this plot, person is defined as someone aged 15 years over.")),
      
      mainPanel(plotOutput("barPlot"), 
                br(),
                plotOutput("lineGraph"),
                strong("The graph above shows the total alcohol consumption per capita for the entire period of the dataset with an intercept line for the consumption in 2017 of 9.39 litres.")
      )
    )
  )


#Assigning server function
server <- function(input, output) {
  #Barplot function
  output$barPlot <- renderPlot({
    #Subsetting dataset to be used in function
    data <- subset(alcohol2, alcohol2$Year == input$Year)
    #ggplot function
    ggplot(data = data, aes(x = Alcohol, y = Volume)) + geom_col(aes(fill = Alcohol), color = "black") + 
      labs(title = "Alcohol Consumption by Popular Types", x = "Type of Alcohol", y = "Volume (Litres)") + 
      theme_bw() + scale_y_continuous(limits = c(0,15), expand = c(0,0)) + 
      scale_fill_manual(values = c("#D8BFD8", "#DA70D6", "#FF00FF", "#9370DB", "#4B0082"))
    
  })
  
  #Line graph function
  output$lineGraph <- renderPlot({
    #Subsetting dataset to be used in function
    data2 <- subset(alcohol2, alcohol2$Alcohol == "Total")
    #ggplot function
    ggplot(data = data2, aes(x = Year, y = Volume, color = Volume)) + geom_line() +  
      labs(title ="Total Alcohol Consumption (1961 - 2017)", x = "Year", y = "Volume (Litres)") + theme_bw() + scale_y_continuous(limits = c(8,15), , expand = c(0,0)) + scale_x_continuous(limits = c(1961, 2020)) + geom_hline(yintercept=9.39, linetype="dashed", color = "red")
  })
  
}

# Deploy app
shinyApp(ui = ui, server = server)