Tutorials Python Python Matplotlib & Plotting
Ch 51 / 58
Python Intermediate 14 min read Chapter 51 of 58

Python Matplotlib & Plotting

Matplotlib is Python's foundational data visualisation library — virtually every Python chart you've seen was made with it, or a library built on top of it (Seaborn, Pandas plots, Plotly). With pyplot, creating beautiful line charts, bar plots, scatter plots, histograms, and multi-panel figures becomes straightforward. Mastering Matplotlib is essential for data analysis, scientific computing, reporting, and building dashboards.

What you'll learn in this chapter
Figure anatomy — Figure, Axes, Artist
pyplot interface — plot, show, save
Line, bar, scatter, histogram & pie charts
Customising — colours, markers, labels, styles
Subplots — multiple axes on one figure
Seaborn integration & Pandas plotting
Advertisement

Figure Anatomy — Understanding the Structure

Every Matplotlib plot is built from a hierarchy of objects. Understanding this structure helps you customise any part of a plot precisely:

Matplotlib object hierarchy — from outermost to innermost
Figure
The entire canvas — outermost container
Created with plt.figure(). Controls overall size (figsize), DPI, background. One figure can contain multiple Axes.
Axes
A single plot area — where data is drawn
Created with fig.add_subplot() or plt.subplots(). Has its own x/y axes, title, limits, and ticks. NOT the same as "Axis"!
Axis
x-axis and y-axis objects inside an Axes
Controls ticks, tick labels, limits (set_xlim, set_ylim), scale (linear, log). Accessed via ax.xaxis, ax.yaxis.
Artist
Everything visible — lines, text, patches
Lines, markers, bars, patches, text annotations — all are Artist objects. The whole hierarchy is composed of Artists.
pyplot
State-machine interface — the easy way
import matplotlib.pyplot as plt. Tracks "current" figure and axes automatically. Good for quick plots; use OOP API for complex figures.

Your First Plot — pyplot Basics

The pyplot interface follows a simple pattern: create data, call a plot function, add labels, show or save. Always install with pip install matplotlib.

Python — first_plot.py
import matplotlib.pyplot as plt
import numpy as np

# ── Minimal line plot ─────────────────────────────────
x = [1, 2, 3, 4, 5]
y = [2, 5, 3, 8, 1]

plt.plot(x, y)
plt.title("My First Plot")
plt.xlabel("X axis")
plt.ylabel("Y axis")
plt.show()                    # displays in window / Jupyter cell

# ── OOP interface (recommended for complex plots) ─────
fig, ax = plt.subplots(figsize=(8, 4))  # Figure + Axes
ax.plot(x, y, color="steelblue", linewidth=2)
ax.set_title("OOP Interface")
ax.set_xlabel("X axis")
ax.set_ylabel("Y axis")
ax.grid(True, alpha=0.3)
plt.tight_layout()             # fix overlapping labels
plt.show()

# ── Save to file ──────────────────────────────────────
fig.savefig("chart.png", dpi=150, bbox_inches="tight")
fig.savefig("chart.pdf")           # vector format for print
fig.savefig("chart.svg")           # SVG for web

# ── Jupyter inline display ────────────────────────────
# %matplotlib inline    ← add in first notebook cell
# %matplotlib widget    ← interactive (ipympl)

Chart Types — When to Use Which

plot()
Trends over time or ordered data
bar()
Comparing categories
scatter()
Relationship between 2 variables
hist()
Distribution of a single variable
pie()
Parts of a whole (use sparingly)
boxplot()
Statistical distribution summary
imshow()
Images and heatmaps
fill_between()
Area charts / confidence bands
Python — chart_types.py
import matplotlib.pyplot as plt
import numpy as np

# ── Bar chart ─────────────────────────────────────────
depts   = ["Eng", "HR", "Sales", "Finance"]
counts  = [12, 5, 8, 4]
fig, ax = plt.subplots()
ax.bar(depts, counts, color=["#4e79a7","#f28e2b","#59a14f","#e15759"])
ax.set_title("Headcount by Department")
ax.set_ylabel("Employees")
plt.show()

# ── Horizontal bar ────────────────────────────────────
ax.barh(depts, counts)   # ← horizontal bar

# ── Scatter plot ──────────────────────────────────────
rng     = np.random.default_rng(42)
x       = rng.normal(0, 1, 100)
y       = 2*x + rng.normal(0, 0.5, 100)
colors  = rng.random(100)

fig, ax = plt.subplots()
sc = ax.scatter(x, y, c=colors, cmap="viridis",
                   alpha=0.7, s=60)
plt.colorbar(sc, ax=ax, label="Value")
ax.set_title("Scatter Plot with Colour Map")
plt.show()

# ── Histogram ─────────────────────────────────────────
data    = rng.normal(0, 1, 1000)
fig, ax = plt.subplots()
ax.hist(data, bins=30, edgecolor="white", color="steelblue", alpha=0.8)
ax.set_title("Normal Distribution")
ax.set_xlabel("Value")
ax.set_ylabel("Frequency")
plt.show()

# ── Pie chart ─────────────────────────────────────────
sizes   = [35, 25, 20, 20]
labels  = ["Eng", "Sales", "HR", "Other"]
explode = (0.05, 0, 0, 0)
fig, ax = plt.subplots()
ax.pie(sizes, labels=labels, explode=explode,
       autopct="%1.1f%%", startangle=90)
plt.show()
Advertisement
K2infocom Python Masterclass & Backend Development
Master Python, Django & Backend APIs with AI
Go from absolute beginner to building production-ready REST APIs, web applications, and ML pipelines. Real projects, live mentoring in Vadodara, and placement support included.
2,400+
Students Enrolled
4.9 ⭐
Google Rating
6 Months
Full Program
100%
Placement Support
Python 3 Matplotlib NumPy & Pandas Data Science Machine Learning Django & DRF Real Projects AI Tools

Customisation — Colours, Markers, Labels & Legends

Matplotlib gives fine-grained control over every visual element. Here are the most commonly used customisation options:

Python — customisation.py
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 2*np.pi, 100)

fig, ax = plt.subplots(figsize=(9, 4))

# ── Plot with style options ───────────────────────────
ax.plot(x, np.sin(x),
         color="#e64040",       # hex colour
         linewidth=2,
         linestyle="--",        # solid, dashed, dotted, dashdot
         marker="o",            # o  s  ^  D  x  +  *
         markersize=4,
         markevery=10,           # marker on every 10th point
         label="sin(x)")

ax.plot(x, np.cos(x),
         color="steelblue",
         linewidth=2,
         label="cos(x)")

# ── Labels, title, limits ─────────────────────────────
ax.set_title("Sine and Cosine", fontsize=14, fontweight="bold")
ax.set_xlabel("x (radians)")
ax.set_ylabel("Amplitude")
ax.set_xlim(0, 2*np.pi)
ax.set_ylim(-1.5, 1.5)

# ── Legend ────────────────────────────────────────────
ax.legend(loc="upper right", fontsize=10)

# ── Grid ──────────────────────────────────────────────
ax.grid(True, linestyle="--", alpha=0.4)
ax.axhline(0, color="black", linewidth=0.8)  # horizontal line at y=0
ax.axvline(np.pi, color="gray", linestyle=":")  # vertical line at x=π

# ── Text annotation ───────────────────────────────────
ax.annotate("Zero crossing",
            xy=(np.pi, 0),          # arrow tip
            xytext=(np.pi+0.3, 0.5),  # text position
            arrowprops=dict(arrowstyle="->", color="gray"),
            fontsize=9, color="gray")

# ── Custom tick labels ────────────────────────────────
ax.set_xticks([0, np.pi/2, np.pi, 3*np.pi/2, 2*np.pi])
ax.set_xticklabels(["0", "π/2", "π", "3π/2", "2π"])

plt.tight_layout()
plt.show()

Subplots — Multiple Plots on One Figure

plt.subplots(rows, cols) creates a grid of Axes on a single Figure. Use plt.subplots_adjust() or plt.tight_layout() to manage spacing.

Python — subplots.py
import matplotlib.pyplot as plt
import numpy as np

rng = np.random.default_rng(42)
x   = np.linspace(0, 10, 100)

# ── 2×2 grid of subplots ─────────────────────────────
fig, axes = plt.subplots(2, 2, figsize=(10, 7))

# Top-left: line chart
axes[0, 0].plot(x, np.sin(x), color="steelblue")
axes[0, 0].set_title("Line — sin(x)")

# Top-right: scatter
axes[0, 1].scatter(rng.random(50), rng.random(50), alpha=0.6)
axes[0, 1].set_title("Scatter")

# Bottom-left: bar
axes[1, 0].bar(["A","B","C"], [5,8,3], color="coral")
axes[1, 0].set_title("Bar Chart")

# Bottom-right: histogram
axes[1, 1].hist(rng.normal(0,1,500), bins=25, color="#59a14f")
axes[1, 1].set_title("Histogram")

plt.tight_layout()
plt.show()

# ── Single row of 3 ──────────────────────────────────
fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(12, 3))

# ── Shared axes ───────────────────────────────────────
fig, (ax1, ax2) = plt.subplots(2, 1,
                                    sharex=True,     # linked x-axis
                                    figsize=(8, 5))
ax1.plot(x, np.sin(x))
ax2.plot(x, np.cos(x), color="coral")
plt.tight_layout()
plt.show()

Styles & Themes

Matplotlib ships with many built-in style sheets that instantly transform the look of your plots. Switch style with plt.style.use().

Python — styles_themes.py
import matplotlib.pyplot as plt
import numpy as np

# ── List all available styles ─────────────────────────
print(plt.style.available)

# ── Popular styles ────────────────────────────────────
# "seaborn-v0_8"    ← clean statistical look
# "ggplot"          ← R ggplot2 inspired
# "dark_background" ← dark mode
# "fivethirtyeight" ← FiveThirtyEight style
# "bmh"             ← Bayesian Methods for Hackers
# "classic"         ← old Matplotlib default

plt.style.use("seaborn-v0_8")

x = np.linspace(0, 10, 100)
plt.plot(x, np.sin(x))
plt.title("Seaborn Style")
plt.show()

# ── Temporary style (context manager) ────────────────
with plt.style.context("dark_background"):
    plt.plot(x, np.sin(x), color="cyan")
    plt.show()
# original style restored here

# ── Colormaps ─────────────────────────────────────────
# Sequential:  viridis, plasma, Blues, YlOrRd
# Diverging:   RdBu, coolwarm, seismic
# Qualitative: Set1, Set2, tab10, Paired
# For data:    avoid jet — use viridis or plasma

# ── rcParams — global settings ───────────────────────
plt.rcParams["figure.figsize"]  = (8, 4)
plt.rcParams["font.family"]     = "DejaVu Sans"
plt.rcParams["axes.grid"]       = True
plt.rcParams["lines.linewidth"]  = 2

Pandas Plotting & Seaborn Integration

Pandas DataFrames have built-in .plot() methods that use Matplotlib under the hood. Seaborn provides higher-level statistical visualisations with a beautiful default style — it's built on Matplotlib so all customisation still works.

Python — pandas_seaborn.py
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

# ── Pandas .plot() ────────────────────────────────────
df = pd.DataFrame({
    "month":   ["Jan","Feb","Mar","Apr","May"],
    "revenue": [120000,145000,98000,167000,182000],
    "costs":   [80000, 90000, 75000, 110000,115000],
})

ax = df.plot(x="month", y=["revenue", "costs"],
              kind="bar", figsize=(8, 4),
              title="Revenue vs Costs", rot=0)
ax.set_ylabel("₹ Amount")
plt.tight_layout()
plt.show()

# kind options: "line", "bar", "barh", "hist", "scatter",
#               "box", "kde", "area", "pie", "hexbin"

# ── Seaborn — statistical plots ───────────────────────
# pip install seaborn
tips = sns.load_dataset("tips")          # built-in sample dataset

# Scatter with regression line
fig, ax = plt.subplots()
sns.regplot(data=tips, x="total_bill", y="tip", ax=ax)
ax.set_title("Bill vs Tip with Regression")
plt.show()

# Box plot by category
fig, ax = plt.subplots()
sns.boxplot(data=tips, x="day", y="total_bill", palette="Set2", ax=ax)
plt.show()

# Heatmap (correlation matrix)
corr = tips.select_dtypes("number").corr()
sns.heatmap(corr, annot=True, cmap="coolwarm", fmt=".2f")
plt.show()

Practice Python Online — Free Compilers

Don't want to install anything yet? Practice all Matplotlib examples from this chapter directly in your browser. Google Colab and JupyterLite have Matplotlib pre-installed and display plots inline.

▶
Online Python 3 Compiler
Write, run and debug Python code in your browser. No installation required. Test every Matplotlib example instantly.
Open Compiler
Replit
Full IDE online
Google Colab
Free GPU notebooks
JupyterLite
Notebooks in browser
Programiz
Beginner-friendly
Chapter Summary
  • Matplotlib hierarchy: Figure (canvas) → Axes (plot area) → Axis (x/y axis) → Artists (lines, text). Install with pip install matplotlib, import as plt.
  • Two interfaces: pyplot (plt.plot()) for quick plots; OOP (fig, ax = plt.subplots()) for complex figures. Prefer OOP for anything serious.
  • Core chart types: plot() (line), bar()/barh() (bar), scatter(), hist(), pie(), boxplot(), imshow().
  • Customise with: color, linewidth, linestyle, marker, alpha. Add labels with set_title(), set_xlabel()/set_ylabel(), legend(), annotate().
  • plt.subplots(rows, cols) creates a grid of Axes. Use sharex=True/sharey=True to link axes. Always call plt.tight_layout() to fix overlaps.
  • Change style globally with plt.style.use("seaborn-v0_8") or temporarily with with plt.style.context(...). Use plt.rcParams for custom global defaults.
  • Pandas df.plot(kind="bar") is a shortcut that uses Matplotlib. You get a Matplotlib Axes back — all customisation still applies.
  • Seaborn (pip install seaborn) provides regplot, boxplot, heatmap, pairplot and more — built on Matplotlib. Save figures with fig.savefig("file.png", dpi=150).
⚡
Free Resource
Download our Python Matplotlib & Plotting Cheat Sheet
Figure anatomy, all chart types, customisation, subplots, styles & Seaborn — one printable page.
Get Sheet
Advertisement
Quick Check — Test Your Understanding
Question & Answer
✓ Answer

A Figure is the entire canvas — the outer container. Think of it as the window or page. It can contain one or many subplots. You control its overall size with figsize and resolution with dpi.

An Axes is a single plot area within the Figure — where your data is actually drawn. It has its own x/y axes, title, ticks, and labels. A Figure with 2×2 subplots has 4 Axes objects.

Common confusion: "Axes" ≠ "Axis". Axes is the plot area; Axis is the x-axis or y-axis object inside it.

✓ Answer

The plt.plot() (pyplot) interface is a state machine — it tracks a "current" figure and axes internally. This works for simple quick plots but becomes problematic with subplots or complex figures.

The OOP interface fig, ax = plt.subplots() gives you direct references to figure and axes objects. You always know exactly which plot you're modifying — no surprises. Use ax.set_title(), ax.set_xlabel() etc. (note the set_ prefix).

✓ Answer

A histogram (hist()) shows the distribution of a single continuous numerical variable — it groups values into bins and shows frequency. Use it to understand how data is distributed.

A bar chart (bar()) compares values across discrete categories. Each bar represents a distinct group. Use it when comparing counts, amounts, or averages across named categories.

✓ Answer

Use fig.savefig() (OOP) or plt.savefig() (pyplot). Important: call it before plt.show() — showing clears the figure.

fig.savefig("chart.png", dpi=150, bbox_inches="tight")
fig.savefig("chart.pdf")   # vector — for print
fig.savefig("chart.svg")   # vector — for web

bbox_inches="tight" prevents labels being cut off. dpi=150 or higher for sharp PNG images.

✓ Answer

plt.tight_layout() automatically adjusts the spacing between subplots (and between subplots and the figure edges) to prevent overlapping titles, labels, and tick marks.

Use it whenever you have: multiple subplots, long x-tick labels that might overlap, or labels that get cut off at the figure edges. Call it just before plt.show() or fig.savefig().

MCQ 1 of 3
Which function creates a Figure with multiple subplots and returns both Figure and Axes objects?
MCQ 2 of 3
When using the OOP interface with fig, ax = plt.subplots(), which method sets the x-axis label?
MCQ 3 of 3
Which of these applies a pre-defined visual style to all subsequent Matplotlib plots?

Rate Us on Google

4.8 / 5
Enjoying this tutorial?
Your 5-star review helps other learners discover our free tutorials and encourages us to keep creating quality content.
80+ reviews
Write a Google Review
Join WhatsApp Channel