Live Population Dashboard

World Population Dashboard (Simulated)

This dashboard showcases a real-time simulation of global population metrics, built using a dummy dataset. While the data is not truly dynamic, it has been manipulated to simulate real-time updates, demonstrating how live population insights could appear in a real-world scenario. Key metrics such as population density, urban population rate, and median age are recalculated on each iteration by replacing the original data with randomly adjusted values at its own locations. This provides a realistic view of how dynamic data could function in a live environment.

The provided code snippet is a Streamlit application for live population analysis. It reads population data from a CSV file and displays key performance indicators (KPIs) and visualizations based on user-selected country data. Here’s a breakdown of the code (explanation are below their respective code snippets) :

import streamlit as st # web development
import pandas as pd # np mean, random
import numpy as np # read csv
import plotly.express as px # build viz
import time # to stimulate real time data
df = pd.read_csv('pop_worldometer_data.csv')
st.set_page_config(
    page_title='Live Population Analysis',
    page_icon='',
    layout='wide'
)

Configures the page title, icon, and layout for the Streamlit application.

st.title('Live Population Analysis')

Sets the main title of the dashboard.

country_filter = st.sidebar.selectbox("Select the Country", pd.unique(df['Country (or dependency)']))

Creates a dropdown sidebar filter that allows users to select a country from the unique entries in the dataset.

placeholder = st.empty()

Initializes a placeholder that will be used for dynamic updates within the application.

df = df[df['Country (or dependency)'] == country_filter]

Filters the DataFrame based on the selected country.

for seconds in range(200):
df['New_Land_Area (Km²)'] = df['Land Area (Km²)'] * np.random.choice(range(1,10),  len(df))
    df['New_Urban_Pop %'] = df['Urban Pop %'] * np.random.choice(range(1,10),  len(df))

#     creating KPIs
    Population_Density = df['Population (2020)'] / df['New_Land_Area (Km²)']
    Urban_Population_Rate = df['New_Urban_Pop %']
    Median_Age = df['Med. Age']*np.random.choice(range(1,10))
  • A loop runs for 200 iterations, simulating real-time data updates. Inside the loop, new columns are generated with random values to modify land area and urban population percentage.
  • KPI Calculations:

    • Computes the following metrics:

      • Population Density: Calculated as the total population divided by the new land area.

      • Urban Population Rate: Taken from the modified urban population percentage.

      • Median Age: Randomly adjusted median age.

Displaying KPIs:

    with placeholder.container():
        kpi1, kpi2, kpi3 = st.columns(3)
    # filling 3 columns with their respective KPIs
        kpi1.metric(label='Population Density', value=round(Population_Density.mean(), 2), delta=round(Population_Density.mean() - 10, 2))
        kpi2.metric(label='Urban Population Rate', value=round(Urban_Population_Rate.mean(), 2), delta=round(Urban_Population_Rate.mean() - 10, 2))
        kpi3.metric(label='Age', value=round(Median_Age.mean(), 2), delta=round(Median_Age.mean() - 10))

Creates three columns to display the KPIs for population density, urban population rate, and median age. The metrics are displayed using Streamlit’s metric function.

 create two columns for charts
        kpi_data = pd.DataFrame({
            'Country': df['Country (or dependency)'],
            'Population Density': Population_Density,
            'Urban Population Rate': Urban_Population_Rate
        })

        # Melt the DataFrame for easier plotting
        kpi_data_melted = kpi_data.melt(id_vars='Country', value_vars=['Population Density', 'Urban Population Rate'])

Prepares a DataFrame for plotting by melting it into a long format suitable for Plotly.

 # Create the bar chart
        fig = px.bar(kpi_data_melted,
                     x='Country',
                     y='value',
                     color='variable',
                     title='Population Density and Urban Population Rate',
                     labels={'value': 'Value'},
                     barmode='group')

        # Display the chart with a unique key
        # To avoid the duplicate key issue, ensure the plot is only created once.
        if 'population_density_urban_rate_chart' not in st.session_state:
            st.session_state['population_density_urban_rate_chart'] = True  # Set a flag

        st.plotly_chart(fig, key=f'population_density_urban_rate_chart_{np.random.randint(1000)}')

Generates a bar chart using Plotly Express, showing population density and urban population rate for the selected country. The chart is displayed in the Streamlit app.

st.markdown('### Detailed Data View')
        st.dataframe(df)

Displays a detailed view of the filtered DataFrame as a table.

   time.sleep(1)

Introduces a delay of half a second between iterations to simulate real-time data updates.

http://localhost:8501/

The dashboard is been running in the localhost.

0
Subscribe to my newsletter

Read articles from Vanshika Nagarajan directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Vanshika Nagarajan
Vanshika Nagarajan