Advertisement
📊 Data Science

Matplotlib Tutorial – Data Visualisation with Python

Matplotlib is Python's foundational plotting library. It can produce publication-quality charts of virtually any type. It forms the base for higher-level libraries like Seaborn, Pandas plotting, and others. Learning Matplotlib fundamentals gives you full control over every visual element.

⏱️ 25 min read🎯 Advanced📅 Updated 2026

Line Plot

The most basic chart type — ideal for trends over time.

Python
import matplotlib.pyplot as plt
import numpy as np

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

plt.figure(figsize=(10, 4))
plt.plot(x, y, color="blue", linewidth=2, label="sin(x)")
plt.plot(x, np.cos(x), color="red", linestyle="--", label="cos(x)")
plt.title("Sine and Cosine")
plt.xlabel("x")
plt.ylabel("y")
plt.legend()
plt.grid(True, alpha=0.3)
plt.savefig("waves.png", dpi=150)
plt.show()

Bar Chart

Compare values across discrete categories.

Python
categories = ["Python", "JavaScript", "Java", "C++", "Go"]
popularity = [30, 25, 20, 10, 5]
colors = ["#3776AB", "#F7DF1E", "#5382A1", "#00599C", "#00ADD8"]

plt.figure(figsize=(8, 5))
bars = plt.bar(categories, popularity, color=colors, edgecolor="white")

# Add value labels on bars
for bar, val in zip(bars, popularity):
    plt.text(bar.get_x() + bar.get_width()/2, bar.get_height() + 0.5,
             f"{val}%", ha="center", fontweight="bold")

plt.title("Programming Language Popularity")
plt.ylabel("Popularity (%)")
plt.tight_layout()
plt.show()

Scatter Plot

Show relationships between two numerical variables.

Python
import numpy as np

np.random.seed(42)
x = np.random.randn(100)
y = 2 * x + np.random.randn(100) * 0.5
colors_arr = np.random.rand(100)

plt.figure(figsize=(7, 5))
plt.scatter(x, y, c=colors_arr, cmap="viridis",
            s=50, alpha=0.7, edgecolors="none")
plt.colorbar(label="Random category")
plt.title("Scatter Plot with Colour Mapping")
plt.xlabel("X variable")
plt.ylabel("Y variable")
plt.show()
Advertisement

Subplots – Multiple Charts

Display multiple charts side by side with subplots().

Python
fig, axes = plt.subplots(1, 2, figsize=(12, 5))

# Chart 1 - Left
axes[0].plot([1,2,3,4], [1,4,9,16], "b-o")
axes[0].set_title("Quadratic")
axes[0].set_xlabel("x")
axes[0].set_ylabel("x²")

# Chart 2 - Right
data = np.random.normal(0, 1, 1000)
axes[1].hist(data, bins=30, color="steelblue", edgecolor="white")
axes[1].set_title("Normal Distribution")

plt.tight_layout()
plt.savefig("subplots.png")
plt.show()

Matplotlib: Two APIs, and Which to Use

Matplotlib is Python's foundational plotting library. The confusion beginners hit: it has two interfaces for the same thing, and mixing them causes mysterious results.

import matplotlib.pyplot as plt

# ✅ Object-oriented API — explicit, scales to complex figures
fig, ax = plt.subplots()
ax.plot(x, y, label="sales")
ax.set_title("Q3"); ax.set_xlabel("month"); ax.legend()
plt.show()

# pyplot API — quick, but uses a hidden "current" figure
plt.plot(x, y); plt.title("Q3"); plt.show()
OO API (ax.)pyplot (plt.)
Styleexplicit fig/axes objectsimplicit "current" figure
Best formulti-plot, reusable codequick one-off charts

Recommendation: learn the object-oriented API (fig, ax = plt.subplots() then call methods on ax). The plt.something() shortcuts operate on a hidden "current" figure, which works for a quick plot but breaks down the moment you have subplots or build charts in functions — you lose track of which figure you're modifying. Key methods differ slightly: it's ax.set_title() on an axes but plt.title() in pyplot. Most other libraries (pandas .plot(), seaborn) sit on top of matplotlib, so these skills transfer.

🏋️ Practical Exercise

Create basic plots:

  1. Draw a line plot of y = x² for x from 0 to 10, with axis labels and a title.
  2. Make a bar chart comparing a few categories.
  3. Create a scatter plot of two related variables.
  4. Combine three charts into one figure using plt.subplots.

🔥 Challenge Exercise

Build a small dashboard figure with plt.subplots(2, 2) showing four views of the same dataset — a line trend, a bar comparison, a scatter, and a histogram. Add titles, axis labels, a shared figure title with suptitle, and a legend where appropriate, then save it to a PNG with savefig. Bonus: customize colors and style with plt.style.use().

📋 Summary

  • Matplotlib is the foundational Python plotting library.
  • The pyplot interface offers quick MATLAB-style commands; the object-oriented interface gives finer control.
  • A Figure is the whole canvas; an Axes is an individual plot within it.
  • plt.subplots() creates a grid of Axes for multiple charts in one figure.
  • Add labels, titles, and legends to make plots readable; save with savefig().
  • Higher-level libraries like Seaborn and pandas plotting build on top of Matplotlib.

Interview Questions on Matplotlib

  • What is Matplotlib used for?
  • What is the difference between the pyplot interface and the object-oriented interface?
  • What is a Figure versus an Axes?
  • How do you create multiple subplots in one figure?
  • How do you save a plot to a file?
  • What are some common plot types and when do you use each?
  • How does Matplotlib relate to libraries like Seaborn and pandas plotting?

FAQ

What is the difference between plt.plot() and the object-oriented API? +

The pyplot (plt) interface keeps a hidden “current” figure and is quick for simple plots. The object-oriented API (fig, ax = plt.subplots()) gives you explicit Figure and Axes objects, which is clearer and recommended for complex, multi-plot figures.

What is the difference between a Figure and an Axes? +

A Figure is the entire image/canvas, which can hold one or more plots. An Axes is a single plot area with its own x/y axes, title, and data. One Figure can contain many Axes.

How do I show plots in a Jupyter notebook? +

Plots usually render inline automatically. If not, add %matplotlib inline. In a script, call plt.show() to open the plot window, or plt.savefig("name.png") to write it to a file.

Should I use Matplotlib or Seaborn? +

Use Seaborn for attractive statistical charts with minimal code; it is built on Matplotlib. Drop down to Matplotlib when you need fine-grained control over every element of the figure.