Data Visualisation with Matplotlib and Seaborn
Why Visualise?
A table of 10,000 numbers tells you almost nothing at a glance. A single chart can reveal a trend, an outlier or a relationship in seconds. Data scientists use charts for two different jobs:
- Exploration: quick, rough charts to understand the data for yourself
- Communication: polished charts that convince a manager at Zenith Bank or a product lead at Spotify to act
Python has two libraries you must know. Matplotlib is the low-level foundation that gives you full control. Seaborn is built on top of it and produces attractive statistical charts in one line.
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np
sns.set_theme(style="whitegrid")
Matplotlib: The Figure and the Axes
Every Matplotlib chart has a Figure (the whole canvas) and one or more Axes (the individual plots). The object-oriented style below is the professional habit, because it scales to multi-panel figures.
months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"]
revenue = [42, 45, 51, 49, 58, 63] # N million
fig, ax = plt.subplots(figsize=(8, 4))
ax.plot(months, revenue, marker="o", color="#EC4899")
ax.set_title("Monthly Revenue, H1 2025")
ax.set_xlabel("Month")
ax.set_ylabel("Revenue (N million)")
plt.show()
Always label the title, the axes and the units. A chart without units is a chart nobody can trust.
The Core Chart Types
| Question you are asking | Chart | Matplotlib / Seaborn |
|---|---|---|
| How does a value change over time? | Line chart | ax.plot / sns.lineplot |
| How do categories compare? | Bar chart | ax.bar / sns.barplot |
| How is one numeric variable distributed? | Histogram | ax.hist / sns.histplot |
| Are two numeric variables related? | Scatter plot | ax.scatter / sns.scatterplot |
| How do distributions compare across groups? | Box plot | sns.boxplot |
| How do many variables correlate? | Heatmap | sns.heatmap |
Picking the right chart is a skill in its own right. The lab below trains you to match a question to a chart type.
Seaborn: Statistical Charts in One Line
Seaborn works directly with DataFrames. You pass the DataFrame and column names, and it handles grouping, colours and legends.
np.random.seed(0)
df = pd.DataFrame({
"bank": np.random.choice(["Access", "GTBank", "Zenith", "UBA"], 400),
"age": np.random.randint(18, 65, 400),
})
df["monthly_spend"] = df["age"] * 2500 + np.random.normal(0, 25000, 400)
# Distribution of one variable
sns.histplot(data=df, x="monthly_spend", bins=30, kde=True)
plt.show()
# Compare distributions across groups
sns.boxplot(data=df, x="bank", y="monthly_spend")
plt.show()
# Relationship between two variables, coloured by a category
sns.scatterplot(data=df, x="age", y="monthly_spend", hue="bank", alpha=0.7)
plt.show()
Multiple Charts in One Figure
Dashboards and reports often place charts side by side:
fig, axes = plt.subplots(1, 2, figsize=(12, 4))
sns.histplot(data=df, x="age", ax=axes[0])
axes[0].set_title("Customer Age Distribution")
sns.barplot(data=df, x="bank", y="monthly_spend", ax=axes[1])
axes[1].set_title("Average Monthly Spend by Bank")
plt.tight_layout()
plt.show()
Correlation Heatmaps
A heatmap of a correlation matrix is one of the fastest ways to scan a dataset for relationships:
corr = df[["age", "monthly_spend"]].corr()
sns.heatmap(corr, annot=True, cmap="RdBu_r", vmin=-1, vmax=1)
plt.show()
Design Rules That Make Charts Better
- Start bar charts at zero. A truncated y-axis exaggerates differences.
- Avoid pie charts with more than 3 or 4 slices. A sorted bar chart is almost always easier to read.
- Use colour with purpose. Highlight the one bar that matters and grey out the rest.
- One message per chart. Put the insight in the title: "USSD transactions fell 18% after the app relaunch" beats "Transactions by channel".
- Save at high resolution for reports:
fig.savefig("chart.png", dpi=200, bbox_inches="tight").
Open in Google Colab
Paste the code blocks above into a new notebook and try changing the chart types, colours and titles. Seaborn and Matplotlib are already available in Colab.
Try it yourself
Key Takeaways
- Matplotlib gives low-level control through Figure and Axes objects, and Seaborn builds on it to produce statistical charts from DataFrames in one line.
- Match the chart to the question: line for trends, bar for comparisons, histogram for distributions, scatter for relationships, box plot for group spread, heatmap for many correlations.
- Always label the title, the axes and the units; put the main insight in the chart title.
- Use plt.subplots to build multi-panel figures, and savefig with a high dpi for reports.
- Start bar axes at zero, avoid crowded pie charts, and use colour to highlight the one thing that matters.
Quick Quiz
1.You want to see whether customer age is related to monthly spend. Which chart is best?
2.Why is fig, ax = plt.subplots() considered better practice than calling plt.plot() directly?
3.Why should bar charts usually start the y-axis at zero?
Ready to go further?
CareerEx gives you structured 12-week training, live classes every Saturday and Sunday, real tutor feedback, and a certificate. Join the next cohort.
Join CareerEx