Python, from Zero, for AILesson 78 of 89

Module 8 · Numbers in bulk: NumPy, pandas and the vector under every model

matplotlib: a plot you can read, saved to a file, from a script or a server

In this lesson

  • 8 min read
  • 7 reading sections
  • Knowledge check
  • Lesson 9 of 10 in this chapter

This chapter’s goalLoad a messy CSV into pandas, clean its missing values and types, group and join it into the table a question needs, convert it to a NumPy array of the right shape and dtype, compute cosine similarity between one vector and a hundred thousand in a single vectorised expression, plot the result to a file, and explain from memory layout why the array version runs a hundred times faster than the loop it replaced.

This chapter’s media

The film explains chapter ideas. The audiobook narrates the complete teaching text.

FormatEnglishहिंदी
Chapter filmWatch1:43Not available
Full audiobookNot availableNot available

A little at a time

Explore an idea, try it, then check what stays.

Step 1 of 9Free · no account needed
Lesson steps

The two-object model

matplotlib has two ways of being used, and most confusion comes from mixing them. The quick way, plt.plot(x, y), draws on an implicit “current figure”. The explicit way creates the objects and draws on them by name:

Python
import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(8, 4))
ax.plot(steps, loss)
ax.set_xlabel("training step")
ax.set_ylabel("loss")
ax.set_title("Loss per step")
fig.savefig("loss.png", dpi=150, bbox_inches="tight")

fig is the canvas; ax is a set of axes on it. Everything you draw goes through ax; everything about the file goes through fig. Learn this form and the implicit one will still make sense when you read it in other people’s code, while the reverse is not true.

bbox_inches="tight" stops the labels being cut off at the edge, which is otherwise the first thing that goes wrong.

Your place and first choices stay on this browser. Classroom credit is recorded separately.

Stuck on something?Ask Divya, your AI tutor

How to cite: Addaly (2026) ‘matplotlib: a plot you can read, saved to a file, from a script or a server’, in Python, from Zero, for AI. Edited by M. Mun. Addaly. Available at: https://addaly.com/learn/python-for-ai/plotting-with-matplotlib (Accessed: 21 November 2026).