Python — Matplotlib
Install & the two APIs
pip install matplotlib
import matplotlib.pyplot as plt
x = [1, 2, 3, 4]
y = [2, 4, 9, 16]
plt.plot(x, y) # line chart
plt.show() # opens a window (or renders in notebook)
plt (pyplot) is the state-machine interface every tutorial uses — start there.
Label your axes — always
plt.plot(x, y, marker="o")
plt.title("Distance over time")
plt.xlabel("Hours")
plt.ylabel("Kilometers")
plt.grid(True)
plt.show()
An unlabeled chart communicates nothing.
The essential chart types
# bar — categories vs values
plt.bar(["Mon", "Tue", "Wed"], [12, 18, 9])
# scatter — relationships between two variables
plt.scatter(heights, weights, alpha=0.5)
# histogram — distribution of ONE variable
plt.hist(exam_scores, bins=10)
# pie — parts of a whole (sparingly!)
plt.pie([60, 40], labels=["Cats", "Dogs"], autopct="%1.0f%%")
| Data question | Chart |
|---|---|
| Trend over time | line |
| Compare categories | bar |
| Correlation of two vars | scatter |
| Shape/spread of one var | histogram |
Multiple lines & legends
plt.plot(months, revenue, label="Revenue")
plt.plot(months, costs, label="Costs")
plt.legend() # shows the labels
Subplots — charts side by side
fig, axes = plt.subplots(1, 2, figsize=(10, 4))
axes[0].plot(x, y)
axes[0].set_title("Left chart")
axes[1].bar(cats, vals)
axes[1].set_title("Right chart")
plt.tight_layout()
plt.show()
Styling quickly
plt.plot(x, y,
color="teal",
linestyle="--",
linewidth=2,
marker="o",
markersize=6)
plt.style.available # list built-in themes
plt.style.use("seaborn-v0_8") # one line → prettier everything
Saving instead of showing
plt.savefig("chart.png", dpi=150, bbox_inches="tight")
Put savefig BEFORE show() (show clears the canvas).
With pandas — one-liner charts
import pandas as pd
df["revenue"].plot(kind="line")
df.groupby("month")["sales"].sum().plot(kind="bar")
df.plot.scatter(x="height", y="weight")
pandas wraps matplotlib so DataFrame columns become plots directly.
Gotchas: forgetting
plt.show()(nothing appears) · savefig after show (empty file) · comparing wildly different scales on one axis.
Mini Practice
- Line chart of temperatures with markers + grid.
- Bar chart of five categories; rotate tick labels via
plt.xticks(rotation=45). - Scatter of two correlated columns from pandas.
- Histogram of 100 random numbers.
- 1×2 subplot figure with titles; save as PNG.
Next: SciPy →
Related Topics
Frequently Asked Questions about Matplotlib
What is Matplotlib in Python?
Matplotlib is a fundamental concept in Python. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Matplotlib?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Matplotlib.
Why is Matplotlib important in Python?
Matplotlib is essential for Python development. Understanding this concept will help you write better code and solve real-world problems more effectively.