0% found this document useful (0 votes)
3 views36 pages

DataVisualization Academic Notes

DATASCIENCE
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views36 pages

DataVisualization Academic Notes

DATASCIENCE
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Data Visualization - Academic Study Notes Matplotlib & Seaborn

Data
Visualization
Complete Academic Notes - Matplotlib & Seaborn

Line Charts Bar Charts Pie Charts Histograms Scatter Plots

Heatmaps Pairplots Distributions Customization Best Practices

Level: Beginner to Intermediate

Includes: Code Real Charts Exercises Interview Q&A;

Libraries: Matplotlib 3.x | Seaborn 0.13.x | Python 3.x

Python Data Visualization | Study Notes Page 1


Data Visualization - Academic Study Notes Matplotlib & Seaborn

Table of Contents

Introduction to Data Visualization 3


* What is Data Visualization?
* Why is it Important?
* Choosing the Right Chart

Setting Up the Environment 4


* Installation
* Importing Libraries
* Figure & Axes Basics

Chapter 1: Line Charts 5


* Single Line
* Multiple Lines
* Customization
* Real-World Example

Chapter 2: Bar Charts 6


* Vertical & Horizontal
* Grouped Bars
* Stacked Bars
* Real-World Example

Chapter 3: Pie Charts 8


* Basic Pie
* Donut Chart
* Exploded Slices
* Real-World Example

1
Chapter 4: Histograms 0
* Frequency Histogram
* Density/KDE
* Bins Explained
* Real-World Example

1
Chapter 5: Scatter Plots 2
* Basic Scatter
* Colour Mapping
* Bubble Chart
* Trend Line

1
Chapter 6: Seaborn Heatmaps 5

Python Data Visualization | Study Notes Page 2


Data Visualization - Academic Study Notes Matplotlib & Seaborn

* Correlation Heatmap
* Pivot Heatmap
* Customization

1
Chapter 7: Seaborn Pairplot 7
* Iris Dataset
* Hue & Diag Kinds
* Interpretation

1
Chapter 8: Distribution Plots 9
* histplot
* kdeplot
* boxplot
* violinplot
2
Matplotlib vs Seaborn 2
* Comparison Table
* When to Use Which

2
Customization Guide 3
* Colours
* Fonts
* Styles
* Subplots

2
Common Mistakes 5
2
Mini Projects & Exercises 6
2
Interview Questions & Answers 8

Python Data Visualization | Study Notes Page 3


Data Visualization - Academic Study Notes Matplotlib & Seaborn

Introduction to Data Visualization


Data visualization is the graphical representation of information and data. By using visual elements like
charts, graphs, and maps, data visualization tools provide an accessible way to see and understand trends,
outliers, and patterns in data. In today's data-driven world, the ability to communicate insights visually is a
core skill for every data scientist, analyst, and developer.

Why is Data Visualization Important?


Faster Understanding -- The human brain processes visuals 60,000x faster than text. A well-made chart
conveys in seconds what a table of numbers takes minutes to understand.
Spot Trends Quickly -- Patterns, correlations, and seasonality hidden in raw data become immediately
obvious when plotted on a line or scatter chart.
Better Decision Making -- Business leaders rely on dashboards and visualizations to make data-driven
decisions instead of gut-feel choices.
Communicate Insights -- Visualizations make it easy to present complex findings to non-technical
stakeholders in a clear and persuasive way.
Identify Outliers -- Anomalies and outliers that would be invisible in a spreadsheet immediately stand out
on a scatter plot or box plot.

Choosing the Right Chart


Chart Type Best For Example Use Case

Line Chart Trends over time Stock prices, monthly sales

Bar Chart Comparing categories Sales by department, votes by party

Pie Chart Part-to-whole relationships Market share, budget breakdown

Histogram Distribution of values Age of customers, exam scores

Scatter Plot Relationships / correlations Height vs weight, ads vs revenue

Heatmap Matrix / correlation data Feature correlations, weekly traffic

Box Plot Spread + outliers Salary by department

Violin Plot Distribution + density Rating by category

The Visualization Landscape -- Chart Types at a Glance

Python Data Visualization | Study Notes Page 4


Data Visualization - Academic Study Notes Matplotlib & Seaborn

Fig 0.1 -- Six core chart types visualised with Python

Python Data Visualization | Study Notes Page 5


Data Visualization - Academic Study Notes Matplotlib & Seaborn

Setting Up the Environment


Before writing any code, install the required libraries:

Terminal

# Install via pip

pip install matplotlib seaborn numpy pandas

# Verify installation

python -c "import matplotlib; print(matplotlib.__version__)"

python -c "import seaborn; print(seaborn.__version__)"

Output

3.8.2

0.13.2

Standard Imports
Python

import [Link] as plt # Core plotting

import [Link] as mpatches

import seaborn as sns # Statistical visualisation

import numpy as np # Numeric arrays

import pandas as pd # DataFrames

# Optional: make plots look nicer in Jupyter

%matplotlib inline

[Link]['[Link]'] = 120

Figure & Axes -- The Building Blocks


Every matplotlib chart has two key objects: a Figure (the entire canvas) and one or more Axes (the individual
plot areas). Understanding this is crucial for customisation.

Python

# Method 1: Quick plot (good for simple charts)

[Link]([1, 2, 3], [4, 5, 6])

[Link]('Quick Plot')

[Link]()

# Method 2: OOP style (recommended for full control)

Python Data Visualization | Study Notes Page 6


Data Visualization - Academic Study Notes Matplotlib & Seaborn

fig, ax = [Link](figsize=(8, 4)) # width=8in, height=4in

[Link]([1, 2, 3], [4, 5, 6])

ax.set_title('OOP Style Plot')

ax.set_xlabel('X Axis')

ax.set_ylabel('Y Axis')

plt.tight_layout() # Auto-adjust spacing

[Link]()

# Multiple subplots

fig, axes = [Link](1, 2, figsize=(12, 4)) # 1 row, 2 cols

axes[0].plot([1,2,3], [4,5,6])

axes[1].bar(['A','B','C'], [3,7,5])

[Link]()

Always use plt.tight_layout() before [Link]() to prevent overlapping labels.

Python Data Visualization | Study Notes Page 7


Data Visualization - Academic Study Notes Matplotlib & Seaborn

Chapter 1 Line Charts


A Line Chart connects data points with a continuous line. It is the go-to chart for showing trends over time
-- how a value changes across ordered categories like days, months, or years.

When to use a Line Chart?


[check] Data is continuous and ordered (time series)
[check] You want to show trends, growth, or decline
[check] Comparing multiple series over the same time period
[check] The x-axis represents a meaningful sequence

Basic Line Chart


Python

import [Link] as plt

import numpy as np

months = ['Jan','Feb','Mar','Apr','May','Jun',

'Jul','Aug','Sep','Oct','Nov','Dec']

sales = [120, 135, 148, 130, 160, 175,

168, 190, 200, 185, 210, 230]

fig, ax = [Link](figsize=(10, 4))

[Link](months, sales,

color='#3F51B5', # Line colour

linewidth=2.5, # Line thickness

marker='o', # Marker shape

markersize=8, # Marker size

label='Sales 2024')

ax.fill_between(months, sales, alpha=0.1, color='#3F51B5')

ax.set_title('Monthly Sales Performance', fontsize=14, fontweight='bold')

ax.set_xlabel('Month')

ax.set_ylabel('Units Sold')

[Link]()

[Link](True, linestyle='--', alpha=0.4)

plt.tight_layout()

Python Data Visualization | Study Notes Page 8


Data Visualization - Academic Study Notes Matplotlib & Seaborn

[Link]()

Fig 1.1 -- Multi-line chart: 2024 Sales by Product (Matplotlib)

Code: Multiple Lines


Python

sales_a = [120, 135, 148, 130, 160, 175, 168, 190, 200, 185, 210, 230]

sales_b = [100, 115, 108, 125, 140, 138, 155, 162, 170, 178, 195, 210]

sales_c = [80, 90, 102, 98, 110, 125, 130, 128, 145, 155, 160, 178]

fig, ax = [Link](figsize=(10, 4))

[Link](months, sales_a, 'o-', color='#3F51B5', lw=2.2, label='Product A')

[Link](months, sales_b, 's-', color='#E91E63', lw=2.2, label='Product B')

[Link](months, sales_c, '^-', color='#4CAF50', lw=2.2, label='Product C')

[Link](); [Link](True, linestyle='--', alpha=0.4)

[Link]()

Key Customisation Options


Parameter What it Controls Example Values

color Line colour 'red', '#3F51B5', (0.2,0.4,0.8)

linewidth Line thickness 1, 2.5, 3

linestyle Dash pattern '-', '--', ':', '-.'

Python Data Visualization | Study Notes Page 9


Data Visualization - Academic Study Notes Matplotlib & Seaborn

marker Data point shape 'o', 's', '^', '*', 'D'

markersize Data point size 4, 8, 12

alpha Transparency 0.0 (invisible) to 1.0 (solid)

label Legend entry 'Revenue', 'Costs'

Python Data Visualization | Study Notes Page 10


Data Visualization - Academic Study Notes Matplotlib & Seaborn

Chapter 2 Bar Charts


A Bar Chart uses rectangular bars to compare values across categories. It is ideal for comparing discrete
groups -- such as sales by region, population by country, or votes by candidate.

Types of Bar Charts


Type Description Best For

Vertical Bar Bars grow upward Comparing categories

Horizontal Bar Bars grow rightward Long category names

Grouped Bar Bars side-by-side per group Comparing sub-groups

Stacked Bar Bars stacked on each other Showing composition

Vertical & Horizontal Bar Chart


Python

import [Link] as plt

departments = ['HR', 'IT', 'Finance', 'Marketing', 'Operations']

avg_salary = [52000, 78000, 65000, 61000, 58000]

colors = ['#3F51B5','#E91E63','#FF9800','#4CAF50','#9C27B0']

fig, axes = [Link](1, 2, figsize=(12, 4))

bars = axes[0].bar(departments, avg_salary,

color=colors, width=0.6, edgecolor='white')

for bar, val in zip(bars, avg_salary):

axes[0].text(bar.get_x() + bar.get_width()/2,

bar.get_height() + 500,

f'${val//1000}K',

ha='center', fontsize=9, fontweight='bold')

axes[0].set_title('Avg Salary by Department')

axes[0].set_ylabel('Salary ($)')

axes[1].barh(departments, avg_salary, color=colors, edgecolor='white')

axes[1].set_title('Horizontal Bar Chart')

axes[1].set_xlabel('Salary ($)')

plt.tight_layout()

Python Data Visualization | Study Notes Page 11


Data Visualization - Academic Study Notes Matplotlib & Seaborn

[Link]()

Fig 2.1 -- Vertical (labelled) & Grouped bar charts

Grouped Bar Chart Code


Python

import numpy as np

quarters = ['Q1', 'Q2', 'Q3', 'Q4']

north = [120, 145, 160, 180]

south = [100, 130, 125, 160]

east = [90, 110, 140, 155]

x = [Link](len(quarters)) # [0, 1, 2, 3]

width = 0.25 # Width of each bar

fig, ax = [Link](figsize=(8, 4))

[Link](x - width, north, width, label='North', color='#3F51B5')

[Link](x, south, width, label='South', color='#E91E63')

[Link](x + width, east, width, label='East', color='#4CAF50')

ax.set_xticks(x)

ax.set_xticklabels(quarters)

ax.set_title('Quarterly Sales by Region')

[Link]()

Python Data Visualization | Study Notes Page 12


Data Visualization - Academic Study Notes Matplotlib & Seaborn

[Link]()

For grouped bars, use [Link]() for x-positions and offset each group by the bar width. This is the standard
pattern.

Python Data Visualization | Study Notes Page 13


Data Visualization - Academic Study Notes Matplotlib & Seaborn

Chapter 3 Pie Charts


A Pie Chart shows the part-to-whole relationship of a dataset. Each slice represents a category's
proportion of the total. Use pie charts sparingly -- they work best with 5 or fewer categories.

Avoid pie charts when differences between slices are small -- a bar chart is almost always easier to read
accurately.

Basic Pie Chart


Python

import [Link] as plt

labels = ['Python', 'JavaScript', 'Java', 'C++', 'Others']

sizes = [35, 28, 18, 12, 7]

colors = ['#3F51B5','#E91E63','#FF9800','#4CAF50','#9C27B0']

explode = (0.05, 0.05, 0, 0, 0) # Slightly pull out first 2 slices

fig, ax = [Link](figsize=(7, 5))

wedges, texts, autotexts = [Link](

sizes,

labels = labels,

autopct = '%1.1f%%', # Show percentage inside slices

colors = colors,

explode = explode,

startangle = 140,

wedgeprops = dict(edgecolor='white', linewidth=1.5)

for autotext in autotexts:

autotext.set_fontweight('bold')

ax.set_title('Programming Language Popularity', fontsize=13, fontweight='bold')

[Link]()

Donut Chart (Pie with a Hole)


Python

fig, ax = [Link](figsize=(6, 5))

[Link](sizes, labels=labels, autopct='%1.1f%%',

Python Data Visualization | Study Notes Page 14


Data Visualization - Academic Study Notes Matplotlib & Seaborn

colors=colors, startangle=90,

wedgeprops=dict(edgecolor='white', linewidth=2))

# Add white circle in the center to make it a donut

centre_circle = [Link]((0, 0), 0.65, color='white')

ax.add_artist(centre_circle)

[Link](0, 0, 'Languages', ha='center', va='center',

fontsize=11, fontweight='bold')

[Link]()

Fig 3.1 -- Standard pie chart (left) & Donut chart with centre label (right)

Python Data Visualization | Study Notes Page 15


Data Visualization - Academic Study Notes Matplotlib & Seaborn

Chapter 4 Histograms
A Histogram shows the frequency distribution of a numerical variable. Unlike a bar chart (which compares
categories), a histogram groups continuous data into bins and counts how many data points fall in each bin.

Understanding Bins
Rule Formula Use When

Square root bins = sqrt(n) General purpose (default)

Sturges bins = 1 + log2(n) Small datasets

Freedman-Diaconis Based on IQR Non-normal distributions

Scott Based on std dev Normal-like distributions

Basic Histogram
Python

import [Link] as plt

import numpy as np

[Link](42)

scores = [Link](loc=72, scale=10, size=300)

fig, ax = [Link](figsize=(9, 4))

n, bins, patches = [Link](

scores, bins=20, color='#3F51B5',

edgecolor='white', linewidth=0.8, alpha=0.85

for patch, val in zip(patches, bins):

if val < 60: patch.set_facecolor('#E91E63')

elif val < 80: patch.set_facecolor('#FF9800')

else: patch.set_facecolor('#4CAF50')

[Link]([Link](scores), color='blue', lw=2, linestyle='--',

label=f'Mean={[Link](scores):.1f}')

[Link]([Link](scores), color='red', lw=2, linestyle=':',

label=f'Median={[Link](scores):.1f}')

ax.set_title('Student Score Distribution', fontsize=13, fontweight='bold')

Python Data Visualization | Study Notes Page 16


Data Visualization - Academic Study Notes Matplotlib & Seaborn

[Link]()

[Link]()

Fig 4.1 -- Colour-coded histogram (left) & Histogram with KDE curve (right)

Reading a Histogram
Shape Meaning Common Example

Bell / Normal Data is symmetric around the Heights, IQ scores


mean

Right-skewed Long tail on the right Income, house prices

Left-skewed Long tail on the left Age at retirement

Bimodal Two peaks -- two groups mixed Exam with two difficulty levels

Uniform All values equally likely Random number generator

Python Data Visualization | Study Notes Page 17


Data Visualization - Academic Study Notes Matplotlib & Seaborn

Chapter 5 Scatter Plots


A Scatter Plot displays individual data points on a two-dimensional grid. It is used to reveal relationships,
correlations, clusters, and outliers between two numeric variables.

Types of Correlation Visible in Scatter Plots


Pattern Description Correlation Value

Points rise left to right Positive correlation r = +0.7 to +1.0

Points fall left to right Negative correlation r = -0.7 to -1.0

Random cloud No correlation r=0

Curved pattern Non-linear relationship r may be near 0

Basic Scatter Plot with Trend Line


Python

import [Link] as plt

import numpy as np

[Link](7)

study_hours = [Link](1, 10, 80)

grades = 55 + study_hours * 4 + [Link](0, 4, 80)

grades = [Link](grades, 50, 100)

fig, ax = [Link](figsize=(8, 5))

scatter = [Link](

study_hours, grades,

c=grades, cmap='RdYlGn', s=70, alpha=0.8,

edgecolors='white', linewidths=0.5

[Link](scatter, label='Grade (%)')

# Add trend line

m, b = [Link](study_hours, grades, 1)

x_line = [Link](1, 10, 100)

[Link](x_line, m*x_line + b, 'b--', lw=2,

label=f'Trend: y={m:.1f}x+{b:.1f}')

Python Data Visualization | Study Notes Page 18


Data Visualization - Academic Study Notes Matplotlib & Seaborn

ax.set_title('Study Hours vs Exam Grade', fontsize=13, fontweight='bold')

[Link]()

[Link]()

Fig 5.1 -- Colour-mapped scatter with trend line (left) & Multi-category scatter (right)

Bubble Chart (3-variable scatter)


Python

countries = ['India','USA','China','Brazil','UK']

gdp = [3.5, 25.0, 18.0, 2.1, 3.1]

life_exp = [70, 79, 77, 75, 82]

population = [1400, 330, 1400, 215, 67]

fig, ax = [Link](figsize=(8, 5))

[Link](gdp, life_exp,

s=[p/3 for p in population], alpha=0.7,

c=[0,1,2,3,4], cmap='tab10')

for i, country in enumerate(countries):

[Link](country, (gdp[i], life_exp[i]),

fontsize=9, ha='center', va='bottom')

ax.set_title('GDP vs Life Expectancy (bubble = population)')

[Link]()

Python Data Visualization | Study Notes Page 19


Data Visualization - Academic Study Notes Matplotlib & Seaborn

Chapter 6 Seaborn Heatmaps


A Heatmap uses colour intensity to display values in a matrix. It is the standard chart for showing correlation
matrices and any data arranged in a grid format. Seaborn's [Link]() makes it trivial to create
beautiful heatmaps.

Correlation Heatmap
Python

import seaborn as sns

import [Link] as plt

import pandas as pd

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

corr = [Link]()

fig, ax = [Link](figsize=(8, 6))

[Link](

corr,

ax=ax,

annot=True, # Show numbers in cells

fmt='.2f', # Format: 2 decimal places

cmap='RdYlGn', # Colour palette

center=0, # 0 = white (neutral)

square=True, # Force square cells

linewidths=0.5,

cbar_kws={'shrink': 0.8}

ax.set_title('Feature Correlation Matrix', fontsize=13, fontweight='bold')

plt.tight_layout()

[Link]()

Python Data Visualization | Study Notes Page 20


Data Visualization - Academic Study Notes Matplotlib & Seaborn

Fig 6.1 -- Correlation heatmap (left) & Pivot table heatmap (right)

Pivot Table Heatmap


Python

pivot = df.pivot_table(

values='sales', index='month',

columns='weekday', aggfunc='mean'

[Link](pivot,

cmap='YlOrRd', annot=True, fmt='.0f',

linewidths=0.5, linecolor='white')

[Link]('Average Sales by Month and Day of Week')

[Link]()

Popular Heatmap Colour Maps


Colormap Best For Notes

RdYlGn Correlation (neg=red, pos=green) Diverging -- set center=0

YlOrRd Frequency / intensity Sequential

Blues Single metric (low=light) Sequential -- clean

Python Data Visualization | Study Notes Page 21


Data Visualization - Academic Study Notes Matplotlib & Seaborn

coolwarm Diverging data Blue=neg, Red=pos

viridis General use Colourblind-friendly

Python Data Visualization | Study Notes Page 22


Data Visualization - Academic Study Notes Matplotlib & Seaborn

Chapter 7 Seaborn Pairplot


A Pairplot creates a grid of scatter plots for every pair of numeric variables in a DataFrame, with distribution
plots on the diagonal. It is a powerful Exploratory Data Analysis (EDA) tool.

Pairplot with the Iris Dataset


Python

import seaborn as sns

import [Link] as plt

iris = sns.load_dataset('iris')

g = [Link](

iris,

hue='species', # Colour points by species

height=2.5,

diag_kind='kde', # Diagonal: KDE instead of histogram

plot_kws={'alpha': 0.7, 's': 40},

palette={

'setosa': '#E91E63',

'versicolor': '#3F51B5',

'virginica': '#4CAF50'

[Link]('Iris Dataset Pairplot', y=1.02,

fontsize=14, fontweight='bold')

[Link]()

Python Data Visualization | Study Notes Page 23


Data Visualization - Academic Study Notes Matplotlib & Seaborn

Fig 7.1 -- Iris pairplot: diagonal=KDE, off-diagonal=scatter by species

How to Read a Pairplot


Cell Position Chart Type What it Shows

Diagonal Histogram / KDE Distribution of a single variable per class

Off-diagonal Scatter plot Relationship between two variables, coloured by class

From the Iris pairplot: petal_length and petal_width separate the three species almost perfectly -- making them
the best features for classification!

Python Data Visualization | Study Notes Page 24


Data Visualization - Academic Study Notes Matplotlib & Seaborn

Chapter 8 Seaborn Distribution Plots


Seaborn provides a family of plots for exploring distributions -- how data is spread and concentrated. These
include histplot, kdeplot, boxplot and violinplot.

Fig 8.1 -- Seaborn distribution plots: histplot, kdeplot, boxplot, violinplot

1. [Link]() -- Enhanced Histogram


Python

[Link](data, bins=25, kde=True,

color='#3F51B5', edgecolor='white')

[Link]('Histplot with KDE Overlay')

2. [Link]() -- Smooth Density Curve

Python Data Visualization | Study Notes Page 25


Data Visualization - Academic Study Notes Matplotlib & Seaborn

Python

[Link](data, color='#3F51B5', lw=2.5, fill=True, alpha=0.25)

[Link]('KDE Plot')

3. [Link]() -- Five-Number Summary


Python

tips = sns.load_dataset('tips')

[Link](data=tips, x='day', y='total_bill', hue='sex',

palette={'Male':'#3F51B5', 'Female':'#E91E63'})

[Link]('Total Bill by Day and Gender')

4. [Link]() -- Distribution + Density


Python

[Link](data=tips, x='day', y='tip', hue='smoker',

split=True,

palette={'Yes':'#FF9800', 'No':'#4CAF50'},

inner='quart')

[Link]('Tip Distribution by Day and Smoker Status')

Choosing Between Distribution Plot Types


Plot Shows When to Use

histplot Frequency counts in bins First look at data distribution

kdeplot Smooth continuous density Comparing multiple distributions


estimate

boxplot Min, Q1, median, Q3, max, outliers Quickly see spread and outliers

violinplot Full distribution shape + box stats When shape matters as much as spread

Python Data Visualization | Study Notes Page 26


Data Visualization - Academic Study Notes Matplotlib & Seaborn

Matplotlib vs Seaborn
Both libraries are essential -- they complement rather than replace each other. Seaborn is built on top of
Matplotlib, so understanding Matplotlib helps you customise Seaborn output.

Feature Matplotlib Seaborn

Purpose Low-level general plotting Statistical visualisation

Syntax More verbose / explicit Concise, DataFrame-aware

Default style Plain white background Beautiful defaults built-in

Statistical plots Manual implementation Built-in (box, violin, heatmap)


needed

Customisation Full control over every detail Good, but limited internals

Pandas support Works, but not optimised Native -- pass df= directly

Learning curve Steeper for complex charts Easier for EDA and stats

Best for Custom, publication-quality Quick EDA, statistical charts


art

Same Chart in Both Libraries


Python

tips = sns.load_dataset('tips')

# Matplotlib (verbose)

fig, ax = [Link](figsize=(8,4))

days = tips['day'].unique()

means = [tips[tips['day']==d]['total_bill'].mean() for d in days]

[Link](days, means, color='#3F51B5', edgecolor='white')

ax.set_title('Avg Bill per Day')

[Link]()

# Seaborn (concise)

fig, ax = [Link](figsize=(8,4))

[Link](data=tips, x='day', y='total_bill',

color='#3F51B5', ax=ax) # CI bars added automatically

ax.set_title('Avg Bill per Day (with 95% CI)')

[Link]()

Python Data Visualization | Study Notes Page 27


Data Visualization - Academic Study Notes Matplotlib & Seaborn

Seaborn's barplot automatically adds 95% confidence interval error bars. Matplotlib requires you to compute and
add them manually.

Python Data Visualization | Study Notes Page 28


Data Visualization - Academic Study Notes Matplotlib & Seaborn

Customization Guide
Good customisation turns a plain chart into a publication-quality visualization. Here are the most important
techniques.

Colours
Python

[Link](x, y, color='steelblue')

[Link](x, y, color='#E91E63')

[Link](x, y, color=(0.24, 0.32, 0.71))

colors = [Link]

for i, col in enumerate(columns):

[Link](x, data[col], color=colors[i])

Annotations & Labels


Python

[Link](x=5, y=150, s='Peak Sales',

fontsize=10, color='red', fontweight='bold')

[Link]('Peak', xy=(5, 200), xytext=(7, 180),

arrowprops=dict(arrowstyle='->', color='black'),

fontsize=10)

[Link](y=100, color='red', linestyle='--', lw=1.5, label='Target')

[Link](xmin=3, xmax=6, alpha=0.15, color='yellow', label='Holiday Season')

Seaborn Themes
Theme Look Best For

whitegrid White bg + grid lines General use

darkgrid Dark bg + grid lines Dense data, presentations

white White bg, no grid Clean publications

dark Dark bg, no grid Dark-mode presentations

ticks Minimal axis ticks Academic papers

Python

sns.set_theme(style='whitegrid', palette='muted', font_scale=1.1)

Python Data Visualization | Study Notes Page 29


Data Visualization - Academic Study Notes Matplotlib & Seaborn

# Available palettes:

# 'deep', 'muted', 'pastel', 'bright', 'dark', 'colorblind'

Saving Figures
Python

[Link]('[Link]', dpi=150, bbox_inches='tight')

[Link]('[Link]', bbox_inches='tight')

[Link]('[Link]', bbox_inches='tight')

[Link]('chart_hires.png', dpi=300, bbox_inches='tight',

facecolor='white', transparent=False)

Python Data Visualization | Study Notes Page 30


Data Visualization - Academic Study Notes Matplotlib & Seaborn

Common Visualization Mistakes


Mistake 1: Truncated Y-Axis
Starting the y-axis at a value other than zero can exaggerate small differences. Always start at zero for bar
charts.

Fix

ax.set_ylim(0, max_val * 1.15) # Start from 0

Mistake 2: Too Many Colours


Using a different colour for every data point creates visual chaos. Use colour purposefully -- to encode a
categorical variable.

Fix

# Use max 5-7 distinct colours; use one colour with varying shades otherwise

Mistake 3: Missing Labels & Titles


A chart without a title, axis labels, or units is incomplete. The reader should never have to guess.

Fix

ax.set_title("Sales by Region Q1 2024") ax.set_xlabel("Region") ax.set_ylabel("Revenue ($)")

Mistake 4: Wrong Chart for the Data


Using a pie chart with 10 slices, or a line chart for unordered categories, confuses instead of clarifies.

Fix

# Ordered time data: Line. Categories: Bar. Proportions (<=5): Pie.

Mistake 5: Overloading with Data


Plotting too many lines or series on one chart creates 'spaghetti plots'. Use subplots instead.

Fix

fig, axes = [Link](2, 2) # Use subplots instead

Mistake 6: Ignoring Colour-Blindness


About 8% of men are colour-blind. Avoid red-green pairs as the only distinction.

Fix

sns.set_palette('colorblind')

Python Data Visualization | Study Notes Page 31


Data Visualization - Academic Study Notes Matplotlib & Seaborn

Mini Projects & Exercises

Mini Project 1: Sales Dashboard


Build a 2x2 dashboard of charts from a single sales dataset:

Python

import [Link] as plt

import seaborn as sns

import pandas as pd

import numpy as np

[Link](42)

n = 200

df = [Link]({

'Month': [Link](['Jan','Feb','Mar','Apr','May','Jun'], n//6+1)[:n],

'Product': [Link](['Laptop','Phone','Tablet'], n),

'Region': [Link](['North','South','East'], n),

'Revenue': [Link](5000, 50000, n),

'Units': [Link](1, 30, n),

})

fig, axes = [Link](2, 2, figsize=(14, 9))

[Link]('Sales Dashboard 2024', fontsize=16, fontweight='bold')

monthly = [Link]('Month')['Revenue'].sum().reindex(

['Jan','Feb','Mar','Apr','May','Jun'])

axes[0,0].plot([Link], [Link], 'o-', color='#3F51B5', lw=2.5)

axes[0,0].set_title('Monthly Revenue')

prod = [Link]('Product')['Revenue'].sum()

axes[0,1].bar([Link], [Link],

color=['#E91E63','#FF9800','#4CAF50'], edgecolor='white')

axes[0,1].set_title('Revenue by Product')

axes[1,0].hist(df['Units'], bins=20, color='#9C27B0', edgecolor='white')

axes[1,0].set_title('Units Sold Distribution')

reg = [Link]('Region')['Revenue'].sum()

axes[1,1].pie([Link], labels=[Link], autopct='%1.1f%%',

Python Data Visualization | Study Notes Page 32


Data Visualization - Academic Study Notes Matplotlib & Seaborn

colors=['#3F51B5','#E91E63','#4CAF50'],

wedgeprops=dict(edgecolor='white'))

axes[1,1].set_title('Revenue by Region')

plt.tight_layout()

[Link]('sales_dashboard.png', dpi=150, bbox_inches='tight')

[Link]()

Practice Exercises
Exercise 1 -- Line Chart
Load daily temperature data for 3 cities over 12 months. Plot all three cities on one line chart with custom
colours, markers, and a shaded area between the hottest and coldest city.

Hint: Use fill_between() for the shaded area.

Exercise 2 -- Bar Chart


Using the Titanic dataset, create a grouped bar chart showing survival count split by passenger class
(Pclass) and gender (Sex).

Hint: groupby(['Pclass','Sex'])['Survived'].sum().unstack().[Link]()

Exercise 3 -- Histogram
Plot the age distribution of Titanic passengers. Colour-code bins: <18 (child), 18-60 (adult), >60 (senior). Add
vertical lines for mean and median.

Hint: Load with sns.load_dataset('titanic'), then use hist() with custom patches.

Exercise 4 -- Heatmap
Create a correlation heatmap for the 'diamonds' Seaborn dataset. Which two numeric variables have the
highest correlation?

Hint: diamonds = sns.load_dataset('diamonds'); [Link]()

Exercise 5 -- Full EDA


Load the 'penguins' dataset. Produce: a pairplot coloured by species, a violin plot of body_mass_g by
species, and a heatmap of numeric correlations.

Hint: penguins = sns.load_dataset('penguins'); dropna() first.

Python Data Visualization | Study Notes Page 33


Data Visualization - Academic Study Notes Matplotlib & Seaborn

Interview Questions & Answers


Q1. What is the difference between Matplotlib and Seaborn?
Matplotlib is a low-level library giving full control over every plot element. Seaborn is built on top of
Matplotlib and provides a higher-level interface with beautiful defaults and built-in statistical plots. Use
Seaborn for quick EDA; use Matplotlib for full customisation.

Q2. When should you use a bar chart vs a line chart?


Use a bar chart when comparing discrete, unordered categories (e.g., sales by region). Use a line chart
when data is continuous and ordered, especially over time. The key: is the x-axis a category or a time
sequence?

Q3. What does a KDE plot show and how is it different from a histogram?
A KDE (Kernel Density Estimate) plot shows a smooth estimate of the probability distribution. A histogram
is discrete (binned counts), while KDE is continuous. KDE is better for comparing multiple distributions
since overlapping curves are easier to read.

Q4. What is a correlation heatmap and how do you interpret it?


A correlation heatmap shows pairwise Pearson correlation coefficients between all numeric columns.
Values range from -1 (perfect negative) to +1 (perfect positive). Values near 0 mean no linear relationship.

Q5. How do you create a chart with multiple subplots in Matplotlib?


Use [Link](rows, cols) which returns a Figure and an array of Axes. Access individual subplots via
axes[row, col]. Use [Link]() for an overall title and plt.tight_layout() to prevent overlap.

Q6. What is the purpose of hue in Seaborn plots?


The hue parameter adds a third dimension by colouring data points or bars by a categorical variable. For
example, [Link](x='age', y='income', hue='gender') colours points by gender.

Q7. How do you save a Matplotlib figure in high resolution?


Use [Link]('[Link]', dpi=300, bbox_inches='tight'). dpi=300 gives print-quality resolution.
bbox_inches='tight' removes whitespace. For vector formats, use .pdf or .svg.

Q8. What is a pairplot and when would you use it?


A pairplot creates a grid of scatter plots for all pairs of numeric columns, with distribution plots on the
diagonal. It is used in EDA to quickly identify which variables are correlated and which separate classes
well.

Q9. How do you plot from a Pandas DataFrame using Seaborn?


Pass the DataFrame to data= and specify column names for x= and y=. For example: [Link](data=df,
x='category', y='value', hue='group'). Seaborn handles grouping and legend creation automatically.

Q10. How do you handle overplotting in scatter plots?


Overplotting can be handled by: (1) reducing alpha (transparency) e.g. alpha=0.3, (2) using jitter with
[Link], (3) using hexbin for very large datasets, (4) sampling a subset of the data.

Python Data Visualization | Study Notes Page 34


Data Visualization - Academic Study Notes Matplotlib & Seaborn

Quick Reference -- Most Used Functions

Matplotlib
Function Purpose Key Parameters

[Link]() Line chart color, lw, marker, linestyle

[Link]() Bar chart color, width, edgecolor

[Link]() Horizontal bar chart color, height

[Link]() Pie chart autopct, explode, startangle

[Link]() Histogram bins, color, edgecolor, density

[Link]() Scatter plot c, s, cmap, alpha

[Link]() Create figure+axes nrows, ncols, figsize

ax.set_title() Plot title fontsize, fontweight, pad

ax.set_xlabel/ylabel() Axis labels fontsize, labelpad

[Link]() Add legend loc, fontsize, title

[Link]() Show grid True/False, linestyle, alpha

[Link]() Save figure dpi, bbox_inches, facecolor

Seaborn
Function Purpose Key Parameters

[Link]() Line chart (with CI) data, x, y, hue

[Link]() Bar chart (with CI) data, x, y, hue, palette

[Link]() Histogram + optional KDE data, bins, kde, color

[Link]() Smooth density curve data, fill, color, bw_adjust

[Link]() Scatter plot data, x, y, hue, size

[Link]() Heatmap annot, fmt, cmap, center

[Link]() Grid of scatter/hist plots data, hue, diag_kind

[Link]() Box plot data, x, y, hue, palette

[Link]() Violin plot data, x, y, split, inner

sns.set_theme() Global style style, palette, font_scale

Python Data Visualization | Study Notes Page 35


Data Visualization - Academic Study Notes Matplotlib & Seaborn

Python Data Visualization | Study Notes Page 37


36

You might also like