Py
PyVizLab
// Data Visualization Mastery
Dash
Plotly
Matplotlib
Seaborn
Folium
Practice Labs
0 / 14 complete
📐
Dash App Structure
Module 1 · Dash Framework
Module 01 — Dash Framework
Building interactive
web apps with Dash
Dash is a Python framework that lets you build data-driven, reactive web applications without writing any JavaScript. It combines Flask, Plotly, and React under the hood.
pip install dash Flask backend React frontend Plotly graphs
Release
2017
by Plotly Inc.
GitHub Stars
21k+
Open source
Components
100+
Built-in + community
Languages
3
Python, R, Julia
✈ Flight Delay Dashboard — localhost:8050
Report Type
Select Year
Airline
Average Monthly Arrival Delay
Carrier Delay
14.2 min
avg per flight
Weather Delay
6.8 min
avg per flight
NAS Delay
9.1 min
avg per flight
1
app = dash.Dash(__name__)
Initializes the Flask + React server. The __name__ helps Dash locate static assets.
2
app.layout = html.Div([...])
Defines the full page DOM tree using Python. html.* mirrors HTML tags, dcc.* adds interactive components.
3
@app.callback(...)
Reactive decorator that wires Input components to Output components. Python replaces JavaScript.
4
app.run_server(debug=True)
Starts the development server with hot reloading. Change to debug=False for production.
Python · app.py
import dash
from dash import dcc, html
from dash.dependencies import Input, Output
import plotly.express as px
import pandas as pd

# ─── Initialize ────────────────────────────────────────────────
app = dash.Dash(__name__)

# ─── Load Data ─────────────────────────────────────────────────
df = pd.read_csv('airline_data.csv')

# ─── Layout ────────────────────────────────────────────────────
app.layout = html.Div([
    html.H1('Flight Delay Time Statistics Dashboard',
           style={'textAlign': 'center', 'color': '#2c3e50'}),

    html.Div([
        dcc.Dropdown(
            id='input-type',
            options=[
                {'label': 'Yearly Statistics',     'value': 'Yearly Statistics'},
                {'label': 'Recession Period',     'value': 'Recession Period'},
            ],
            value='Yearly Statistics',
        ),
        dcc.Dropdown(
            id='input-year',
            options=[{'label': i, 'value': i} for i in range(1980, 2024)],
            value=2010,
        ),
    ], style={'display': 'flex', 'gap': '20px', 'margin': '20px'}),

    html.Div(id='output-container')
])

# ─── Callback ──────────────────────────────────────────────────
@app.callback(
    Output('output-container', 'children'),
    [Input('input-type', 'value'),
     Input('input-year', 'value')]
)
def update_output(report_type, year):
    if report_type == 'Yearly Statistics':
        return create_yearly_charts(year)
    return create_recession_charts()

if __name__ == '__main__':
    app.run_server(debug=True)
Module 01 — Lesson 2
Dash Core Components
& HTML elements
dcc (Dash Core Components) and html provide building blocks for your UI. Try interacting with the live demos below — each one shows the real component behavior.
dcc.Dropdown
Select a chart type:
dcc.Slider
Select year:
2019
dcc.RadioItems
Report type:
Yearly
Recession
Monthly
dcc.Checklist
Delay types:
Carrier Delay
Weather Delay
NAS Delay
dcc.DatePickerRange
Date range:
dcc.Input
Enter airline code:
Python · components.py
from dash import dcc, html

# Dropdown ─────────────────────────────────────────────────────
dcc.Dropdown(id='airline-select',
    options=[{'label': name, 'value': code}
             for name, code in AIRLINE_CODES.items()],
    multi=True, placeholder='Select airlines...')

# RangeSlider ──────────────────────────────────────────────────
dcc.RangeSlider(id='year-range',
    min=2010, max=2023, step=1, value=[2015, 2020],
    marks={i: str(i) for i in range(2010, 2024, 2)})

# RadioItems ───────────────────────────────────────────────────
dcc.RadioItems(id='chart-type',
    options=[{'label': t, 'value': t}
             for t in ['Bar', 'Line', 'Scatter']],
    value='Line', inline=True)

# Graph ────────────────────────────────────────────────────────
dcc.Graph(id='main-chart',
    style={'height': '400px'},
    config={'displayModeBar': False})
Module 01 — Lesson 3
Reactive Callbacks:
wiring everything together
Callbacks are the heart of Dash. They define reactive data flows — when an Input changes, Dash automatically calls your function and updates the Output. No page reload needed.
Single Input → Output
One control updates one chart. The simplest pattern.
🔀
Multiple Inputs
Several controls combine to update one Output. Use a list of Input() decorators.
🌊
Multiple Outputs
One callback returns values for several Output targets simultaneously.
🔗
Chained Callbacks
Output of one callback becomes Input of another. Enables dynamic dropdowns.
💾
State vs Input
State reads a value without triggering the callback. Useful for forms.
🚀
Pattern Matching
ALL, MATCH, and ALLSMALLER enable callbacks on dynamic component IDs.
Python · callbacks.py
from dash.dependencies import Input, Output, State

# ── Pattern 1: Multiple Outputs ────────────────────────────────
@app.callback(
    [Output('carrier-chart', 'figure'),
     Output('weather-chart', 'figure'),
     Output('nas-chart',     'figure'),
     Output('security-chart','figure'),
     Output('late-ac-chart', 'figure')],
    [Input('year-input', 'value')]
)
def update_all_delay_charts(selected_year):
    filtered = df[df['Year'] == selected_year]

    carrier_fig  = px.line(filtered, x='Month', y='CarrierDelay',
                             title=f'Carrier Delay — {selected_year}')
    weather_fig  = px.line(filtered, x='Month', y='WeatherDelay',
                             title=f'Weather Delay — {selected_year}')
    nas_fig      = px.bar(filtered,  x='Month', y='NASDelay')
    security_fig = px.bar(filtered,  x='Month', y='SecurityDelay')
    late_ac_fig  = px.line(filtered, x='Month', y='LateAircraftDelay')

    return carrier_fig, weather_fig, nas_fig, security_fig, late_ac_fig

# ── Pattern 2: Chained Callbacks ───────────────────────────────
@app.callback(
    Output('airline-dropdown', 'options'),
    Input('year-dropdown',    'value')
)
def update_airline_options(selected_year):
    # Dynamic options based on year selection
    airlines = df[df['Year'] == selected_year]['Airline'].unique()
    return [{'label': a, 'value': a} for a in airlines]
Module 02 — Plotly Express
One-line charts
with Plotly Express
Plotly Express (px) provides a high-level API for creating interactive charts with minimal code. Each chart type supports hover, zoom, pan, and export out of the box.
Chart Type
Dataset
Monthly Average Airline Delays — Line Chart LIVE
Python · plotly_charts.py
import plotly.express as px
import pandas as pd

df = pd.read_csv('airline_data.csv')

# Line chart ───────────────────────────────────────────────────
fig = px.line(df.groupby('Month')['ArrDelay'].mean().reset_index(),
    x='Month', y='ArrDelay',
    title='Monthly Avg Arrival Delay',
    color_discrete_sequence=px.colors.qualitative.Plotly)
fig.update_layout(hovermode='x unified', template='plotly_dark')

# Bar chart ────────────────────────────────────────────────────
fig2 = px.bar(df.groupby('Airline')['ArrDelay'].mean().reset_index(),
    x='Airline', y='ArrDelay',
    color='ArrDelay', color_continuous_scale='blues',
    title='Average Delay by Carrier')

# Scatter ──────────────────────────────────────────────────────
fig3 = px.scatter(df, x='DepDelay', y='ArrDelay',
    color='Airline', size='Distance',
    hover_data=['Origin', 'Dest'],
    title='Departure vs Arrival Delay')
Module 02 — Lesson 2
Advanced Interactivity
& Graph Objects
Go beyond px with go.Figure for full control. Add custom hover templates, annotations, shapes, and multi-axis layouts for production-grade charts.
🖱
Hover Templates
Custom HTML templates for rich hover tooltips with hovertemplate=
📐
Annotations
Add text, arrows, and shapes to highlight key data points.
📊
Dual Y-Axis
Layer different scales with secondary_y=True in make_subplots.
🎨
Color Scales
Built-in Viridis, Plasma, Blues, and custom hex color sequences.
📱
Responsive Layout
autosize=True with responsive=True in Dash Graph config.
💾
Export
Export PNG, SVG, or interactive HTML with fig.write_html()
Python · advanced_plotly.py
import plotly.graph_objects as go
from plotly.subplots import make_subplots

fig = make_subplots(specs=[[{"secondary_y": True}]])

fig.add_trace(go.Bar(
    x=months, y=passengers,
    name="Passengers (M)",
    marker_color='#38BDF8',
    hovertemplate="Month: %{x}<br>Passengers: %{y:.1f}M<extra></extra>"
))

fig.add_trace(go.Scatter(
    x=months, y=delays,
    name="Avg Delay (min)", mode="lines+markers",
    line={"color": "#F472B6", "width": 3}
), secondary_y=True)

fig.add_annotation(x="Jul", y=max(delays),
    text="Peak summer delays ✈",
    arrowcolor="#FBBF24", font={"color": "#FBBF24"})

fig.update_layout(template="plotly_dark", hovermode="x unified")
fig.write_html("interactive_delays.html")
Module 03 — Matplotlib
Publication-quality
static visualizations
Matplotlib is the bedrock of Python visualization. While other libraries build on top of it, understanding Matplotlib directly gives you full control over every pixel of your figures.
Plot Type
Style
Automobile Sales (2010–2020) — Line Plot MATPLOTLIB
Python · matplotlib_plots.py
import matplotlib.pyplot as plt
import numpy as np

plt.style.use('seaborn-v0_8-darkgrid')
fig, ax = plt.subplots(figsize=(12, 5))

# Line plot with confidence interval ──────────────────────────
ax.plot(years, sales, 'o-', color='#F472B6',
       linewidth=2.5, markersize=8, label='Sales')
ax.fill_between(years, lower, upper, alpha=0.15, color='#F472B6')

# Annotations
ax.annotate('COVID dip',
    xy=(2020, sales[-1]), xytext=(2018, 68000),
    arrowprops={'arrowstyle': '->', 'color': 'gray'},
    fontsize=10, color='gray')

ax.set_xlabel('Year', fontsize=12)
ax.set_ylabel('Units Sold', fontsize=12)
ax.set_title('Automobile Sales 2010–2020', fontsize=16, fontweight='bold')
ax.legend()
plt.tight_layout()
plt.savefig('sales_trend.png', dpi=300, bbox_inches='tight')
Module 03 — Lesson 2
Subplots & Figure
composition
plt.subplots() and GridSpec let you compose complex multi-panel figures. Essential for comparative analysis dashboards and reports.
2×2 Subplot Grid — Automobile DashboardMATPLOTLIB
Python · subplots.py
fig, axes = plt.subplots(2, 2, figsize=(14, 10))
fig.suptitle('Automobile Sales Dashboard', fontsize=18)

axes[0,0].plot(years, sales)
axes[0,0].set_title('Annual Sales')

axes[0,1].bar(categories, values, color=colors)
axes[0,1].set_title('Sales by Category')

axes[1,0].scatter(price, demand, alpha=0.6)
axes[1,0].set_title('Price vs Demand')

axes[1,1].pie(market_share, labels=brands, autopct='%1.1f%%')
axes[1,1].set_title('Market Share')

plt.tight_layout()
Module 04 — Seaborn
Statistical distributions
made beautiful
Seaborn builds on Matplotlib to create statistically meaningful, aesthetically refined charts with far less code. Perfect for EDA (exploratory data analysis).
Plot Type
Dataset
Bins: 20
Iris — Histogram SEABORN
Python · seaborn_dist.py
import seaborn as sns
import matplotlib.pyplot as plt

iris = sns.load_dataset('iris')

# Histogram with KDE overlay ───────────────────────────────────
sns.histplot(data=iris, x='sepal_length', hue='species',
             kde=True, bins=25, palette='husl')
plt.title('Sepal Length Distribution by Species')

# Violin plot ──────────────────────────────────────────────────
fig, axes = plt.subplots(1, 2, figsize=(12, 5))
sns.violinplot(data=iris, x='species', y='sepal_length',
               palette='muted', inner='quartile', ax=axes[0])
sns.boxplot(data=iris,    x='species', y='sepal_width',
               palette='Set2',  notch=True,            ax=axes[1])

# Pair plot ────────────────────────────────────────────────────
pair_grid = sns.pairplot(iris, hue='species',
    diag_kind='kde', plot_kws={'alpha': 0.6})
Module 04 — Lesson 2
Categorical
visualization patterns
Seaborn's categorical plots (barplot, stripplot, swarmplot, countplot) reveal patterns across categories with built-in confidence intervals and aggregation.
Restaurant Tips — Avg Bill by Day & Smoker StatusSEABORN
Module 04 — Lesson 3
Regression & correlation
plots
sns.regplot, lmplot, and heatmap reveal statistical relationships. Correlation heatmaps using sns.heatmap are essential for feature engineering in ML pipelines.
Tips Dataset — Tip vs Total Bill (with regression)SEABORN
Module 05 — Folium
Interactive maps
powered by Leaflet.js
Folium bridges Python data and Leaflet.js maps. Generate fully interactive HTML maps from pandas DataFrames with just a few lines of Python.
Tile Layer
Location
Zoom: 12
Python · folium_maps.py
import folium

# Basic map ────────────────────────────────────────────────────
m = folium.Map(location=[40.7128, -74.0060],
               zoom_start=12,
               tiles='CartoDB positron')

# Custom tile providers
folium.TileLayer('CartoDB dark_matter').add_to(m)
folium.TileLayer('Stamen Terrain').add_to(m)
folium.LayerControl().add_to(m)

# Add a circle marker
folium.CircleMarker(
    location=[40.7128, -74.0060],
    radius=8, color='#FB923C', fill=True,
    popup=folium.Popup('<b>NYC</b><br>Population: 8.3M',
                         max_width=200)
).add_to(m)

m.save('nyc_map.html')
Module 05 — Lesson 2
Markers, Clusters
& Popups
Add rich markers with HTML popups, MarkerClusters for dense data, CircleMarkers sized by value, and FeatureGroups for toggle-able layers.
Python · markers.py
from folium.plugins import MarkerCluster, HeatMap

# Marker cluster ───────────────────────────────────────────────
cluster = MarkerCluster().add_to(m)

airports = df[df['type'] == 'large_airport']
for _, row in airports.iterrows():
    popup_html = f"""
    <b>{row['name']}</b><br>
    IATA: {row['iata_code']}<br>
    Country: {row['iso_country']}
    """
    folium.Marker(
        location=[row['latitude_deg'], row['longitude_deg']],
        popup=folium.Popup(popup_html, max_width=250),
        icon=folium.Icon(color='blue', icon='plane', prefix='fa')
    ).add_to(cluster)

# Heat map ─────────────────────────────────────────────────────
heat_data = [[row['lat'], row['lon'], row['weight']]
             for _, row in df.iterrows()]
HeatMap(heat_data, radius=15).add_to(m)
Practice Labs — Quiz
Test your knowledge
across all modules
Answer questions covering Dash, Plotly, Matplotlib, Seaborn, and Folium. Each correct answer explains the concept in depth.
Practice Labs — Assignment
Build the Airline Delay
Dashboard
Complete the callback function that powers a five-chart airline delay statistics dashboard. Your code will be validated for structure and correctness.
✈ Airline Statistics Dashboard — Target Output
Year Input
2019
Carrier Delay
Weather Delay
NAS Delay
Security Delay
Late Aircraft
📄 callback_solution.py
Python 3.10