DSP_Exp03_Visualization [Link]
html
Experiment 03: Data Visualization with Python
Libraries: matplotlib, seaborn, pandas, numpy, pywa�e, wordcloud
In [56]: import numpy as np, pandas as pd
import [Link] as plt, matplotlib as mpl
import seaborn as sns
from pywaffle import Waffle
from wordcloud import WordCloud
import warnings; [Link]('ignore')
sns.set_style("whitegrid")
print("Libraries imported!")
Libraries imported!
Section A: Introduction to Visualization Tools
A.1 Introduction to Data Visualization
Data Visualization is the graphical representation of data using charts, graphs, and maps.
• Humans process visuals 60,000× faster than text
• Helps identify trends, patterns, and outliers
• Types: Comparison (bar/line), Composition (pie/area), Distribution (histogram/box), Relationship (scatter/bubble)
A.2 Introduction to Matplotlib
1 of 20 18/03/26, 23:11
DSP_Exp03_Visualization [Link]
Matplotlib is Python's most popular 2D plotting library (created by John D. Hunter, 2003).
• pyplot — MATLAB-like interface | Figure — the canvas | Axes — the plot area
• Architecture: Backend Layer → Artist Layer → Scripting Layer (pyplot)
In [57]: # Matplotlib Figure & Subplots
fig, axes = [Link](1, 2, figsize=(10, 3))
axes[0].text(0.5, 0.5, 'Subplot 1', ha='center', va='center', fontsize=16)
axes[0].set_title("Left Panel")
axes[1].text(0.5, 0.5, 'Subplot 2', ha='center', va='center', fontsize=16)
axes[1].set_title("Right Panel")
[Link]("Matplotlib Subplots Demo", fontweight='bold')
plt.tight_layout(); [Link]()
A.4 Dataset on Immigration to Canada
Using immigration data for selected countries from 1980 to 2013 (34 years).
In [58]: # Immigration to Canada Dataset (selected countries, 1980-2013)
years = list(range(2016, 2025))
data = {
2 of 20 18/03/26, 23:11
DSP_Exp03_Visualization [Link]
'India': [8880,8670,8147,7338,5704,4211,7150,10189,11522],
'China': [5123,6682,3308,1863,1527,1816,1960,2643,2758],
'Pakistan': [1201,900,668,514,691,1072,1334,2261,2470],
}
df = [Link](data, index=[str(y) for y in years])
df_canada = df.T
df_canada['Total'] = df_canada.sum(axis=1)
print("Dataset loaded —", df_canada.shape)
df_canada
Dataset loaded — (3, 10)
Out[58]: 2016 2017 2018 2019 2020 2021 2022 2023 2024 Total
India 8880 8670 8147 7338 5704 4211 7150 10189 11522 71811
China 5123 6682 3308 1863 1527 1816 1960 2643 2758 27680
Pakistan 1201 900 668 514 691 1072 1334 2261 2470 11111
A.5 Line Plots
A Line Plot shows trends over time using connected data points.
In [73]: # Line Plot — Top 5 Countries Immigration Trend
years_str = [str(y) for y in range(2016, 2025)]
[Link](figsize=(10, 5))
for country in df_canada.index:
[Link](range(len(years_str)), df_canada.loc[country, years_str].values, linewidth=2, label=country)
[Link](range(0, 9, 3), [years_str[i] for i in range(0, 9, 3)])
[Link]('Year');
[Link]('Immigrants')
[Link]('Immigration to Canada (2014-2024)', fontweight='bold')
[Link](fontsize=9); [Link](alpha=0.3)
plt.tight_layout(); [Link]()
3 of 20 18/03/26, 23:11
DSP_Exp03_Visualization [Link]
Section B: Basic Visualization Tools
B.1 Area Plots
An Area Plot �lls the region between a line and the x-axis. Stacked area plots show part-to-whole over time.
4 of 20 18/03/26, 23:11
DSP_Exp03_Visualization [Link]
In [60]: # Stacked Area Plot
df_top = df_canada.drop('Total', axis=1).T
df_top.index = range(2016, 2025)
df_top.plot(kind='area', stacked=True, figsize=(10, 5), alpha=0.6, colormap='Set2')
[Link]('Year'); [Link]('Immigrants')
[Link]('Stacked Area Plot — Immigration to Canada', fontweight='bold')
[Link](loc='upper left', fontsize=9)
plt.tight_layout(); [Link]()
B.2 Histograms
5 of 20 18/03/26, 23:11
DSP_Exp03_Visualization [Link]
A Histogram shows the distribution of numerical data by grouping values into bins.
In [ ]: # Histogram — Total Immigration Distribution
[Link](figsize=(8, 4))
[Link](df_canada['Total'], bins=8, color='#3498db', edgecolor='white', alpha=0.8)
[Link](df_canada['Total'].mean(),color='red',linestyle='--',label=f"Mean: {df_canada['Total'].mean():,.0f}")
[Link]('Total Immigrants'); [Link]('Frequency')
[Link]('Distribution of Total Immigration', fontweight='bold')
[Link](); [Link](alpha=0.3)
plt.tight_layout(); [Link]()
B.3 Bar Charts
A Bar Chart compares categorical data using rectangular bars.
6 of 20 18/03/26, 23:11
DSP_Exp03_Visualization [Link]
In [74]: # Bar Chart — Total Immigration by Country
[Link](figsize=(8, 4))
# colors = ['#e74c3c','#3498db','#2ecc71','#9b59b6','#f39c12']
bars = [Link](df_canada.index, df_canada['Total'], color=colors, edgecolor='white')
for b in bars:
[Link](b.get_x()+b.get_width()/2, b.get_height()+1000, f'{b.get_height():,.0f}',
ha='center', fontsize=9, fontweight='bold')
[Link]('Total Immigrants')
[Link]('Total Immigration to Canada by Country', fontweight='bold')
[Link](rotation=20); [Link](axis='y', alpha=0.3)
plt.tight_layout(); [Link]()
Section C: Specialized Visualization Tools
7 of 20 18/03/26, 23:11
DSP_Exp03_Visualization [Link]
C.1 Pie Charts
A Pie Chart shows proportions of a whole as circular slices.
In [78]: # Pie Chart — Immigration Proportions
[Link](figsize=(7, 7))
explode = [0.05]*3; explode[df_canada['Total'].[Link]()] = 0.12
[Link](df_canada['Total'], labels=df_canada.index, autopct='%1.1f%%',
startangle=140, )
[Link]('Immigration Proportions (1980–2013)', fontweight='bold', pad=15)
plt.tight_layout(); [Link]()
8 of 20 18/03/26, 23:11
DSP_Exp03_Visualization [Link]
9 of 20 18/03/26, 23:11
DSP_Exp03_Visualization [Link]
C.2 Box Plots
A Box Plot displays the �ve-number summary: min, Q1, median, Q3, max — plus outliers.
In [84]: # Box Plot — Immigration Distribution by Country
yearly = df_canada.drop('Total', axis=1).[Link](float)
[Link](figsize=(8, 5))
bp = [Link]([yearly[c].values for c in [Link]], patch_artist=True, labels=[Link],
medianprops=dict(color='black', linewidth=2))
[Link]('Immigrants')
[Link]('Box Plot — Immigration Distribution')
[Link](axis='y', alpha=0.3)
plt.tight_layout(); [Link]()
10 of 20 18/03/26, 23:11
DSP_Exp03_Visualization [Link]
C.3 Scatter Plots
A Scatter Plot shows the relationship between two numerical variables using dots.
In [ ]: # Scatter Plot — 1980 vs 2013 Immigration
[Link](figsize=(7, 5))
x, y = df_canada['2016'].astype(float), df_canada['2024'].astype(float)
[Link](x, y, s=120, c='#3498db', edgecolors='white', linewidth=2, alpha=0.8)
for country in df_canada.index:
11 of 20 18/03/26, 23:11
DSP_Exp03_Visualization [Link]
[Link](country, (df_canada.loc[country,'2016'], df_canada.loc[country,'2024']),
fontsize=9, xytext=(5,5), textcoords='offset points')
[Link]([0, [Link]()*1.1], [0, [Link]()*1.1], '--', color='gray', alpha=0.4)
[Link]('Immigrants in 2016'); [Link]('Immigrants in 2024')
[Link]('Scatter — 2016 vs 2024 Immigration', fontweight='bold')
[Link](alpha=0.3)
plt.tight_layout(); [Link]()
C.4 Bubble Plots
12 of 20 18/03/26, 23:11
DSP_Exp03_Visualization [Link]
A Bubble Plot is a scatter plot where marker size encodes a 3rd variable.
In [ ]: # Bubble Plot — x=2016, y=2024, size=Total
[Link](figsize=(8, 6))
total = df_canada.drop('Total', axis=1).sum(axis=1).astype(float)
sizes = (total / [Link]()) * 1500
x_data = df_canada.drop('Total', axis=1)['2016'].astype(float)
y_data = df_canada.drop('Total', axis=1)['2024'].astype(float)
[Link](x_data, y_data,
s=sizes, alpha=0.6, edgecolors='black', linewidth=1.5)
for i, c in enumerate(x_data.index):
[Link](c, (x_data.iloc[i], y_data.iloc[i]),
ha='center', va='center', fontsize=9, fontweight='bold')
[Link]('2016'); [Link]('2024')
[Link]('Bubble Plot (size = Total Immigrants)', fontweight='bold')
[Link](alpha=0.3)
plt.tight_layout(); [Link]()
13 of 20 18/03/26, 23:11
DSP_Exp03_Visualization [Link]
Section D: Advanced Visualization Tools
14 of 20 18/03/26, 23:11
DSP_Exp03_Visualization [Link]
D.1 Wa�e Charts
A Wa�e Chart uses a grid of squares to show proportions — an alternative to pie charts.
Library: pywaffle
In [111… # Waffle Chart — Immigration Proportions
values_for_waffle = df_canada['Total'].to_dict()
fig = [Link](FigureClass=Waffle, rows=5, columns=5,
values=values_for_waffle,
title={'label':'Waffle Chart — Immigration to Canada',},
labels=[f"{k} ({v:,})" for k,v in values_for_waffle.items()],
legend={'bbox_to_anchor':(1,-0),'ncol':3,},
figsize=(12,6))
plt.tight_layout(); [Link]()
15 of 20 18/03/26, 23:11
DSP_Exp03_Visualization [Link]
D.2 Word Clouds
A Word Cloud displays text where word size = frequency/importance.
16 of 20 18/03/26, 23:11
DSP_Exp03_Visualization [Link]
Library: wordcloud
In [126… # Word Cloud — Country names sized by immigration total
wc = WordCloud()
wc.generate_from_frequencies(df_canada['Total'].to_dict())
[Link]()
[Link](wc); [Link]('off')
[Link]('Word Cloud — Immigration to Canada', )
plt.tight_layout(); [Link]()
D.3 Seaborn
Seaborn is a high-level statistical visualization library built on Matplotlib.
• Beautiful defaults, works with DataFrames, built-in statistical estimation
• Key plots: heatmap , boxplot , violinplot , pairplot , barplot
17 of 20 18/03/26, 23:11
DSP_Exp03_Visualization [Link]
In [136… # Seaborn — Heatmap (correlation) & Violin Plot
fig = [Link](figsize=(14, 5))
# Heatmap
corr = [Link]()
[Link](corr, annot=True, cmap='coolwarm', fmt='.2f', linewidths=1, square=True)
[Link]('Heatmap — Country Correlation', fontweight='bold')
# Violin Plot
# melted = [Link](var_name='Country', value_name='Immigrants')
# [Link](data=melted, x='Country', y='Immigrants', palette='Set2', inner='box', ax=axes[1])
# axes[1].set_title('Violin Plot — Distribution', fontweight='bold')
# axes[1].tick_params(axis='x', rotation=20)
plt.tight_layout(); [Link]()
18 of 20 18/03/26, 23:11
DSP_Exp03_Visualization [Link]
D.4 Regression Plots
A Regression Plot �ts a best-�t line to data with a con�dence interval.
• [Link]() — simple regression | [Link]() — residuals | order — polynomial degree
In [155… # Regression Plot — India Immigration Trend
years_regression = [str(y) for y in range(2016, 2025, 2 )]
india_df = [Link]({'Year': range(2016, 2025, 2 ),
19 of 20 18/03/26, 23:11
DSP_Exp03_Visualization [Link]
'Immigrants': df_canada.loc['India', years_regression].astype(float).values})
fig, axes = [Link](1, 2, figsize=(14, 5))
[Link](data=india_df, x='Year', y='Immigrants',
ax=axes[0])
axes[0].set_title('Linear Regression — India',)
[Link](data=india_df, x='Year', y='Immigrants',
order=2, ax=axes[1])
axes[1].set_title('Polynomial Regression (order=2) — India', )
plt.tight_layout(); [Link]()
20 of 20 18/03/26, 23:11