Skip to main content

Creating Interactive Dashboards with R Shiny: A Step-by-Step Guide

In the world of data visualisation and analysis, R Shiny has emerged as a powerful tool for creating interactive web applications directly from R. Today, we will walk through the process of building a dashboard to visualise acute malnutrition data in Nigeria's BAY (Borno, Adamawa, and Yobe) states. This guide will provide insights into the structure and implementation of a Shiny dashboard, using our simple malnutrition analysis project as a practical example.

Dataset Details

For this dashboard, we used the Nigeria Acute Malnutrition Data set, which provides valuable information on Severe Acute Malnutrition (SAM) and Moderate Acute Malnutrition (MAM) cases across different states and Local Government Areas (LGAs) in Nigeria for the year 2023. This dataset focuses on the BAY (Borno, Adamawa, and Yobe) states, which have been significantly affected by ongoing humanitarian challenges.

Dataset Source

The dataset is available from the OCHA (United Nations Office for the Coordination of Humanitarian Affairs) Services website. It's part of the Humanitarian Data Exchange (HDX) platform, which is an open platform for sharing data across crises and organizations.

Link to Dataset

For those interested in practicing with this dataset or creating their own visualizations, you can access the dataset at the following link:

Raw dataset: Nigeria Acute Malnutrition Data on HDX

Cleaned dataset: malnut

Data Structure

The dataset includes the following key columns:

- State

- LGA (Local Government Area)

- SAM (Severe Acute Malnutrition) cases

- MAM (Moderate Acute Malnutrition) cases

This structure allows for analysis at both the state and LGA levels, providing a comprehensive view of the malnutrition situation in the region.

The Dashboard Link

The interactive dashboard created using this dataset and the R Shiny code discussed in this blog post is publicly available. You can explore the live version of the dashboard at the following link:

Acute Malnutrition Dashboard

I encourage readers to interact with the dashboard to get a feel for its functionality and to see firsthand how Shiny can transform raw data into an engaging, interactive experience.

By exploring this dashboard, you can:

1. Select specific states or LGAs to focus your analysis

2. View the distribution of SAM cases across states

3. Identify the top 10 LGAs affected by SAM and MAM

4. Compare total SAM and MAM cases across states

This practical example serves as an excellent starting point for those looking to create their own data visualization projects using R Shiny. Whether you're working with public health data or any other dataset, the principles and techniques demonstrated here can be adapted to suit a wide range of analytical needs.

Now lets get started!

Setting Up the R Environment

Before diving into the dashboard creation, it's crucial to set up our R environment with the necessary libraries. For this project, we'll be using the following packages:

library(shiny)

library(readxl)

library(shinydashboard)

library(dplyr)

library(ggplot2)

library(plotly)

library(rsconnect)

library(sass)

Each of these libraries serves a specific purpose:

shiny: The core library for building interactive web applications

readxl: For reading Excel files

shinydashboard: Provides additional UI components for creating dashboard layouts

dplyr: For data manipulation

ggplot2 and plotly: For creating static and interactive plots

rsconnect: For deploying Shiny applications

sass: For advanced CSS styling (optional)

Data Preparation

The first step in any data visualization project is to load and prepare the data. In our case, we're working with an Excel file containing malnutrition data:

malnut <- read_excel("malnut.xlsx")

It's often necessary to clean and preprocess the data at this stage, although the specifics will depend on your dataset.

Building the User Interface

Shiny applications consist of two main components: the user interface (UI) and the server logic. Let's start with the UI.

For our dashboard, we're using the shinydashboard package to create a professional-looking layout:

ui <- dashboardPage(

  dashboardHeader(title = "Acute Malnutrition in BAY States"),

  dashboardSidebar(

    selectInput("state", "Select State:", 

                choices = c("All", unique(malnut$state))),

    selectInput("lga", "Select LGA:", 

                choices = c("All", unique(malnut$lga)))

  ),

  dashboardBody(

    fluidRow(

      column(12, align="center",

             h2("Acute Malnutrition in the BAY States of Nigeria, 2023")

      )

    ),

    fluidRow(

      column(6, plotlyOutput("pie_chart")),

      column(6, plotlyOutput("sam_bar_chart"))

    ),

    fluidRow(

      column(6, plotlyOutput("mam_bar_chart")),

      column(6, plotlyOutput("total_cases_chart"))

    )

  )

)

This UI code creates a dashboard with:

  1. A header with the dashboard title
  2. A sidebar with dropdown menus for selecting state and LGA
  3. A body containing four plots arranged in a grid layout

The plotlyOutput function is used to create placeholders for our interactive plots.

Implementing Server Logic

The server function is where we define the reactive behavior of our application and create the visualizations:

server <- function(input, output, session) {

    # Reactive dataset based on selections

  filtered_data <- reactive({

    data <- malnut

    if (input$state != "All") {

      data <- data %>% filter(state == input$state)

    }

    if (input$lga != "All") {

      data <- data %>% filter(lga == input$lga)

    }

    data

  })

  

  # Update LGA choices based on selected state

  observeEvent(input$state, {

    if (input$state == "All") {

      lga_choices <- c("All", unique(malnut$lga))

    } else {

      lga_choices <- c("All", unique(malnut$lga[malnut$state == input$state]))

    }

    updateSelectInput(session, "lga", choices = lga_choices)

  })

  

  # Pie Chart: SAM by State

  output$pie_chart <- renderPlotly({

    data <- filtered_data() %>%

      group_by(state) %>%

      summarise(sam = sum(sam))

    

    plot_ly(data, labels = ~state, values = ~sam, type = 'pie') %>%

      layout(title = "Severe Acute Malnutrition by State")

  })

  

  # ... (code for other plots)

}

Key components of the server function include:

  1. A reactive expression (filtered_data) that filters the dataset based on user selections
  2. An observeEvent to update the LGA dropdown based on the selected state
  3. Multiple renderPlotly functions to create the interactive plots

Each plot is created using plotly, which allows for interactive features like hovering and zooming.

Running the Application

To run the Shiny application, we use the shinyApp function:

shinyApp(ui = ui, server = server)

This combines our UI and server components and launches the interactive dashboard.

Advanced Features and Considerations

  1. Reactivity: Shiny's reactive programming model is a key feature. In our example, the filtered_data reactive expression ensures that our plots update automatically when the user changes the state or LGA selection.
  2. Performance: For large datasets, consider using techniques like data.table or dbplyr to improve performance.
  3. Styling: While shinydashboard provides a nice default look, you can further customize the appearance using CSS or the sass package.
  4. Deployment: Once your dashboard is ready, you can deploy it to a Shiny server or a service like shinyapps.io for public access.

Conclusion

Building interactive dashboards with R Shiny offers a powerful way to explore and present data. This example demonstrates how to create a multi-faceted dashboard for analyzing acute malnutrition, but the same principles can be applied to a wide range of data visualisation projects.

By leveraging the interactivity of Shiny and the visualization capabilities of ggplot2 and plotly, we've created a tool that allows users to gain insights into complex data with ease. Whether you're working in public health, business analytics, or any other data-driven field, mastering Shiny can significantly enhance your ability to communicate insights effectively.

We encourage readers to explore the full code of this dashboard and experiment with their own datasets. The possibilities for creating impactful, interactive visualizations with R Shiny are truly endless.



Comments

Post a Comment