Python Data Visualization
15 Exercises — Complete Study Guide
Scatter · Hexbin · Contour · Line · Heatmap · Histogram · Box Plot · Violin
Muhammad Hammad Hafeez
Data Science · University of Okara, Pakistan
Python Data Visualization — 15 Exercises | Muhammad Hammad Hafeez | University of Okara | Page 1 of 18
Table of Contents
Section A: Global Patterns in Data
Ex 01 Basic Scatter Plot [Scatter Plots]
Ex 02 Scatter — Colour by Category [Scatter Plots]
Ex 03 Hexagonal Binning Plot [Hexbin Plots]
Ex 04 Contour Plot [Contour Plots]
Ex 05 Basic Line Plot [Line Plots]
Ex 06 Multiple Line Plots [Line Plots]
Ex 07 Correlation Heatmap [Heatmaps]
Ex 08 Heatmap with Linkage [Heatmaps]
Section B: Summary Statistics
Ex 09 Basic Histogram [Histogram]
Ex 10 Histogram + KDE Overlay [Histogram]
Ex 11 Box Plot by Category [Box Plots]
Ex 12 Violin Plot by Category [Violin Plots]
Ex 13 Scatter + Regression Line [Scatter Plots]
Ex 14 Shaded Area Line Plot [Line Plots]
Ex 15 Summary Dashboard [All Types]
Python Data Visualization — 15 Exercises | Muhammad Hammad Hafeez | University of Okara | Page 2 of 18
Section A — Global Patterns in Data
Exercise 01 · Scatter Plot (Basic)
Topic: Scatter Plots
A scatter plot shows the relationship between two numeric variables. Each dot = one data row. Good for spotting
correlations, clusters, and outliers.
import [Link] as plt
import numpy as np
x = [Link](20, 60, 300) # Age
y = [Link](30000, 120000, 300) # Salary
[Link](x, y, color='steelblue', alpha=0.6, edgecolors='white')
[Link]('Age')
[Link]('Salary ($)')
[Link]('Age vs Salary')
[Link]()
Exercise 02 · Scatter — Colour by Category
Topic: Scatter Plots
We loop over each category, filter the data, and plot with a different colour. This adds a 3rd dimension (category) to
the scatter.
import [Link] as plt
import pandas as pd, numpy as np
df = [Link]({
'Age': [Link](20, 60, 300),
'Salary': [Link](30000, 120000, 300),
'Dept': [Link](['HR','IT','Finance','Mktg'], 300)
})
colors = {'HR':'blue','IT':'orange','Finance':'green','Mktg':'purple'}
for dept, grp in [Link]('Dept'):
[Link](grp['Age'], grp['Salary'],
label=dept, color=colors[dept], alpha=0.7)
[Link]()
Python Data Visualization — 15 Exercises | Muhammad Hammad Hafeez | University of Okara | Page 3 of 18
[Link]('Age'); [Link]('Salary')
[Link]('Age vs Salary by Department')
[Link]()
Exercise 03 · Hexagonal Binning Plot
Topic: Hexbin Plots
When thousands of points overlap in a scatter, hexbin divides space into hexagons and colours them by count —
showing data density clearly.
import [Link] as plt
import numpy as np
x = [Link](20, 60, 300)
y = [Link](70, 10, 300).clip(0, 100)
[Link](x, y, gridsize=20, cmap='Blues')
[Link](label='Count')
[Link]('Age'); [Link]('Score')
[Link]('Hexagonal Binning — Age vs Score')
[Link]()
Python Data Visualization — 15 Exercises | Muhammad Hammad Hafeez | University of Okara | Page 4 of 18
Exercise 04 · Contour Plot
Topic: Contour Plots
A contour plot shows a 3D surface on 2D using colour bands (contourf) and lines (contour). Great for density or
Z-values across an X-Y grid.
import [Link] as plt
import numpy as np
x = [Link](20, 60, 100)
y = [Link](30000, 120000, 100)
xx, yy = [Link](x, y)
zz = [Link](xx / 10) * [Link](yy / 20000)
[Link](xx, yy, zz, levels=12, cmap='RdYlBu')
[Link]()
[Link](xx, yy, zz, levels=12,
colors='black', linewidths=0.4, alpha=0.4)
[Link]('Age'); [Link]('Salary Range')
[Link]('Contour Plot')
[Link]()
Python Data Visualization — 15 Exercises | Muhammad Hammad Hafeez | University of Okara | Page 5 of 18
Exercise 05 · Basic Line Plot
Topic: Line Plots
A line plot connects ordered points — perfect for time-series. fill_between() shades under the line to show magnitude.
import [Link] as plt
months = ['Jan','Feb','Mar','Apr','May','Jun',
'Jul','Aug','Sep','Oct','Nov','Dec']
sales = [120,135,128,150,160,175,180,170,155,145,165,190]
[Link](months, sales, color='steelblue',
marker='o', linewidth=2.5, markersize=6)
plt.fill_between(months, sales, alpha=0.15, color='steelblue')
[Link]('Month'); [Link]('Sales')
[Link]('Monthly Sales')
[Link](rotation=30)
[Link]()
Python Data Visualization — 15 Exercises | Muhammad Hammad Hafeez | University of Okara | Page 6 of 18
Exercise 06 · Multiple Line Plots
Topic: Line Plots — Multiple Series
Plot multiple lines on the same axes to compare different series — Sales, Expenses, and Profit together using different
colours and markers.
import [Link] as plt
months = ['Jan','Feb','Mar','Apr','May','Jun',
'Jul','Aug','Sep','Oct','Nov','Dec']
sales = [120,135,128,150,160,175,180,170,155,145,165,190]
expenses = [80, 90, 85,100,105,110,115,108, 95, 98,110,130]
profit = [s-e for s,e in zip(sales, expenses)]
[Link](months, sales, color='blue', marker='o', label='Sales')
[Link](months, expenses, color='red', marker='s', label='Expenses')
[Link](months, profit, color='green', marker='^', label='Profit')
[Link]()
[Link]('Month'); [Link]('Amount (K)')
[Link]('Sales / Expenses / Profit')
[Link](rotation=30)
[Link]()
Python Data Visualization — 15 Exercises | Muhammad Hammad Hafeez | University of Okara | Page 7 of 18
Exercise 07 · Correlation Heatmap
Topic: Heatmaps
[Link]() colours a grid by value. A correlation matrix heatmap shows instantly which variable pairs are strongly
related (warm = positive, cool = negative).
import seaborn as sns
import pandas as pd, numpy as np, [Link] as plt
df = [Link]([Link](300, 4),
columns=['Age','Salary','Score','Hours'])
corr = [Link]()
[Link](corr, annot=True, fmt='.2f',
cmap='coolwarm', linewidths=0.5)
[Link]('Correlation Matrix Heatmap')
[Link]()
Python Data Visualization — 15 Exercises | Muhammad Hammad Hafeez | University of Okara | Page 8 of 18
Exercise 08 · Heatmap with Linkage (Clustermap)
Topic: Heatmaps — Linkage
[Link]() reorders rows/columns by similarity using hierarchical clustering. The dendrogram tree on the side
shows the LINKAGE structure.
import seaborn as sns
import pandas as pd, numpy as np
df = [Link]([Link](300, 4),
columns=['Age','Salary','Score','Hours'])
g = [Link]([Link](),
cmap='viridis',
figsize=(7, 6),
dendrogram_ratio=0.2)
[Link]('Heatmap with Linkage', y=1.02)
[Link]()
Python Data Visualization — 15 Exercises | Muhammad Hammad Hafeez | University of Okara | Page 9 of 18
Python Data Visualization — 15 Exercises | Muhammad Hammad Hafeez | University of Okara | Page 10 of 18
Section B — Summary Statistics of Data
Exercise 09 · Basic Histogram
Topic: Histograms
A histogram bins continuous data and counts values per bin. It reveals the shape of the distribution — normal, skewed,
or bimodal.
import [Link] as plt
import numpy as np
scores = [Link](70, 10, 300).clip(0, 100)
[Link](scores, bins=20, color='steelblue',
edgecolor='white', alpha=0.85)
[Link]('Score')
[Link]('Frequency')
[Link]('Score Distribution — Histogram')
[Link]()
Exercise 10 · Histogram + KDE Overlay
Topic: Histograms (Revisited)
Setting density=True converts bars to density. A KDE (Kernel Density Estimate) curve on top gives a smooth version
of the distribution.
import [Link] as plt
import numpy as np
from scipy import stats
scores = [Link](70, 10, 300).clip(0, 100)
[Link](scores, bins=20, density=True,
color='steelblue', edgecolor='white', alpha=0.7)
kde_x = [Link]([Link](), [Link](), 200)
kde_y = stats.gaussian_kde(scores)(kde_x)
[Link](kde_x, kde_y, color='orange',
linewidth=2.5, label='KDE')
Python Data Visualization — 15 Exercises | Muhammad Hammad Hafeez | University of Okara | Page 11 of 18
[Link]('Score'); [Link]('Density')
[Link]()
[Link]('Histogram + KDE Overlay')
[Link]()
Exercise 11 · Box Plot by Category
Topic: Box Plots
A box plot shows Q1, median, Q3, whiskers, and outliers. Comparing boxes across departments reveals salary spread
differences at a glance.
import [Link] as plt
import pandas as pd, numpy as np
df = [Link]({
'Salary': [Link](30000, 120000, 300),
'Dept': [Link](['HR','IT','Finance','Mktg'], 300)
})
depts = df['Dept'].unique()
data = [df[df['Dept']==d]['Salary'].values for d in depts]
[Link](data, tick_labels=depts, patch_artist=True)
[Link]('Department')
[Link]('Salary ($)')
[Link]('Box Plot — Salary by Department')
[Link]()
Python Data Visualization — 15 Exercises | Muhammad Hammad Hafeez | University of Okara | Page 12 of 18
Exercise 12 · Violin Plot by Category
Topic: Violin Plots
A violin = box plot + KDE. The wider the violin at a point, the more data there is at that value. Shows full distribution
shape, not just the 5-number summary.
import [Link] as plt
import pandas as pd, numpy as np
df = [Link]({
'Score': [Link](70, 10, 300).clip(0, 100),
'Dept': [Link](['HR','IT','Finance','Mktg'], 300)
})
depts = df['Dept'].unique()
data = [df[df['Dept']==d]['Score'].values for d in depts]
vp = [Link](data, showmedians=True)
[Link](range(1, len(depts)+1), depts)
[Link]('Department')
[Link]('Score')
[Link]('Violin Plot — Score by Department')
[Link]()
Python Data Visualization — 15 Exercises | Muhammad Hammad Hafeez | University of Okara | Page 13 of 18
Exercise 13 · Scatter + Regression Line
Topic: Scatter Plots — Advanced
[Link]() fits a straight line to the scatter. The R value (printed in legend) shows correlation strength: 1 =
perfect, 0 = none, -1 = inverse.
import [Link] as plt
import numpy as np
from scipy import stats
hours = [Link](1, 12, 300)
scores = [Link](70, 10, 300).clip(0, 100)
m, b, r, *_ = [Link](hours, scores)
xr = [Link]([Link](), [Link](), 100)
[Link](hours, scores, color='steelblue', alpha=0.5, s=40)
[Link](xr, m*xr + b, color='red',
linewidth=2.5, label=f'R = {r:.2f}')
[Link]()
[Link]('Hours Studied'); [Link]('Score')
[Link]('Scatter + Regression Line')
[Link]()
Python Data Visualization — 15 Exercises | Muhammad Hammad Hafeez | University of Okara | Page 14 of 18
Exercise 14 · Shaded Area Line Plot
Topic: Line Plots — Advanced
fill_between() fills the space between two lines. Used to show confidence intervals, expected ranges, or just add visual
weight to a time series.
import [Link] as plt
months = ['Jan','Feb','Mar','Apr','May','Jun',
'Jul','Aug','Sep','Oct','Nov','Dec']
sales = [120,135,128,150,160,175,180,170,155,145,165,190]
upper = [s + 15 for s in sales]
lower = [s - 15 for s in sales]
[Link](months, sales, color='steelblue',
linewidth=2.5, marker='o', markersize=6)
plt.fill_between(months, lower, upper,
alpha=0.2, color='steelblue', label='+/-15 range')
[Link]()
[Link]('Month'); [Link]('Sales')
[Link]('Sales with Uncertainty Range')
[Link](rotation=30)
[Link]()
Python Data Visualization — 15 Exercises | Muhammad Hammad Hafeez | University of Okara | Page 15 of 18
Exercise 15 · Summary Dashboard — All Types
Topic: All Plot Types
GridSpec or [Link]() lets you combine multiple chart types into one figure — a dashboard. This brings together all
7 chart types from both sections.
import [Link] as plt
import seaborn as sns, numpy as np, pandas as pd
fig, axes = [Link](2, 3, figsize=(14, 8))
[Link]('Summary Dashboard', fontsize=14, fontweight='bold')
axes[0,0].scatter(age, salary, color='blue', alpha=0.5, s=15)
axes[0,0].set_title('Scatter: Age vs Salary')
axes[0,1].plot(months, sales, color='orange', marker='o')
axes[0,1].set_title('Line: Monthly Sales')
axes[0,2].hist(scores, bins=15, color='green', edgecolor='white')
axes[0,2].set_title('Histogram: Score')
axes[1,0].boxplot(data_by_dept, tick_labels=depts, patch_artist=True)
axes[1,0].set_title('Box Plot: Salary')
axes[1,1].violinplot(data_by_dept, showmedians=True)
axes[1,1].set_title('Violin: Score')
[Link](corr, annot=True, fmt='.2f',
cmap='coolwarm', ax=axes[1,2])
axes[1,2].set_title('Heatmap: Correlation')
plt.tight_layout(); [Link]()
Python Data Visualization — 15 Exercises | Muhammad Hammad Hafeez | University of Okara | Page 16 of 18
Python Data Visualization — 15 Exercises | Muhammad Hammad Hafeez | University of Okara | Page 17 of 18
Quick Reference — Cheat Sheet
Plot Type Function Best Used For
Scatter [Link](x, y) Relationship between 2 variables
Hexbin [Link](x, y) Dense scatter (1000+ points)
Contour [Link](x,y,z) 3-D surface on 2-D grid
Line [Link](x, y) Trends over time / ordered data
Heatmap [Link](data) Correlation / matrix values
Clustermap [Link](data) Heatmap + hierarchical linkage
Histogram [Link](data) Distribution of one variable
Box Plot [Link](data) 5-number summary by group
Violin [Link](data) Full distribution shape by group
fill_between plt.fill_between(x,y) Uncertainty / range shading
Regression [Link](x,y) Trend line on scatter
Python Data Visualization — 15 Exercises | Muhammad Hammad Hafeez | University of Okara | Page 18 of 18