Line Plot
The most basic chart type — ideal for trends over time.
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.
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.
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()Subplots – Multiple Charts
Display multiple charts side by side with subplots().
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.) | |
|---|---|---|
| Style | explicit fig/axes objects | implicit "current" figure |
| Best for | multi-plot, reusable code | quick 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:
- Draw a line plot of
y = x²for x from 0 to 10, with axis labels and a title. - Make a bar chart comparing a few categories.
- Create a scatter plot of two related variables.
- 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
pyplotinterface 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
pyplotinterface 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?
Related Topics
FAQ
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.
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.
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.
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.

