Matplotlib · Chapter 2 of 16
Inside a figure
By the end of this chapter you can say what a Figure holds inside (its Axes, and in each Axes the lines, the texts, two axis objects, four spines and a legend), tell pyplot's "current" chart apart from the ax you hold, name each line in a legend, add a light grid, and read every one of those things back from a chart with its get_ methods. Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.
- Part: The first chart
- 4 tasks
- Matplotlib
- Free chapter
Free with a Google or GitHub sign-in, like the first 2 chapters of every lab.
Why you need this
Ira wants the cities side by side. Two lines on one Axes is chapter 1: two calls of ax.plot. But a chart of Ghaziabad and Faridabad in December, drawn that way, is a blue line and an orange line, and nothing on the chart says which city is which. A principal in Ghaziabad who reads the wrong one thinks her worst day was 251 when it was 295.
<!-- chart: !Two lines of December's PM2.5, blue and orange, with nothing to say which city is which -->
There is a second problem in Jaspreet's old scripts. They were written in pyplot's other style, plt.title(...) instead of ax.set_title(...), and the weekly report has gone out more than once with a title on the wrong chart. To see why, you need to know what is inside a Figure and how pyplot decides where to draw.
And Tanvir's Check, which has read your charts since chapter 1, never looks at a picture: it asks the Figure what it holds. By the end of this chapter you can do that too.
The lesson
Everything on a chart is an object
The story's example is December 2025 in Ghaziabad. city_daily.csv has one row per city per day; a mask picks December's rows and then one city's:
import matplotlib.pyplot as plt
import pandas as pd
city = pd.read_csv("/workspace/data/city_daily.csv")
december = city[city["date"].str.startswith("2025-12")]
ghaziabad = december[december["city"] == "Ghaziabad"]["pm25"].tolist()
days = list(range(1, 32))
fig, ax = plt.subplots()
ax.plot(days, ghaziabad, label="Ghaziabad")
ax.set_title("PM2.5 in December 2025")
ax.legend()
Now ask the Figure what it holds, in IPython. get_children() lists the objects one level down:
In [12]: fig.get_children()
Out[12]:
[<matplotlib.patches.Rectangle at 0xffff6e69da90>,
<Axes: title={'center': 'PM2.5 in December 2025'}>]
In [13]: ax.get_children()
Out[13]:
[<matplotlib.lines.Line2D at 0xffff6e6aa710>,
<matplotlib.spines.Spine at 0xffff6e69e900>,
<matplotlib.spines.Spine at 0xffff6e6aae90>,
<matplotlib.spines.Spine at 0xffff6e6aafd0>,
<matplotlib.spines.Spine at 0xffff6e6ab110>,
<matplotlib.axis.XAxis at 0xffff6e69eba0>,
<matplotlib.axis.YAxis at 0xffff6e69f0e0>,
Text(0.5, 1.0, 'PM2.5 in December 2025'),
Text(0.0, 1.0, ''),
Text(1.0, 1.0, ''),
<matplotlib.legend.Legend at 0xffff6e738830>,
<matplotlib.patches.Rectangle at 0xffff6e729950>]
The Figure holds a Rectangle (its white background, fig.patch) and the one Axes. The Axes holds much more:
- the Line2D that
ax.plotmade; - four Spines, the lines that frame the chart, in
ax.spinesby name:list(ax.spines)is['left', 'right', 'bottom', 'top']; - two axis objects,
ax.xaxis(anXAxis) andax.yaxis(aYAxis): each one owns its ticks, its tick labels and its label; - three Text objects for titles: the centre one says 'PM2.5 in December 2025', and two empty ones wait on the left and the right;
- the Legend, and the Axes' own background Rectangle (
ax.patch).
Every one of these is an Artist, Matplotlib's word for anything that can draw itself. When you save, the Figure asks each of its Artists to draw, each asks its own children, and so on down the tree. That is all a chart is, and it is why every part of it can be read back or changed later: it is an object you can reach.
pyplot's own drawing, and the current Axes
You will meet Matplotlib code written in a second style, with pyplot's own functions and no ax at all:
In [2]: plt.get_fignums()
Out[2]: []
In [3]: plt.plot([1, 2, 3], [211.6, 124.0, 219.5])
Out[3]: [<matplotlib.lines.Line2D at 0xffffa4561450>]
In [4]: plt.title("Ghaziabad, 1 to 3 December")
Out[4]: Text(0.5, 1.0, 'Ghaziabad, 1 to 3 December')
In [5]: plt.gcf()
Out[5]: <Figure size 640x480 with 1 Axes>
In [6]: plt.gca()
Out[6]: <Axes: title={'center': 'Ghaziabad, 1 to 3 December'}>
There was no figure (plt.get_fignums() lists the open ones, and the list was empty), so plt.plot made one. pyplot keeps a current Figure and a current Axes, which plt.gcf() and plt.gca() ("get current figure", "get current axes") return, and plt.plot, plt.title, plt.xlabel and the rest all draw on the current Axes. Underneath, they are the same Axes methods: plt.title(...) is plt.gca().set_title(...).
Which Axes is current? The last one made, unless you change it. With two charts open, that is a trap:
In [2]: fig_gzb, ax_gzb = plt.subplots()
In [3]: fig_fbd, ax_fbd = plt.subplots()
In [4]: plt.gcf() is fig_fbd
Out[4]: True
In [5]: plt.gca() is ax_fbd
Out[5]: True
In [6]: ax_gzb.plot([1, 2, 3], [211.6, 124.0, 219.5])
Out[6]: [<matplotlib.lines.Line2D at 0xffffacc6d1d0>]
In [7]: plt.title("Ghaziabad")
Out[7]: Text(0.5, 1.0, 'Ghaziabad')
In [8]: ax_gzb.get_title()
Out[8]: ''
In [9]: ax_fbd.get_title()
Out[9]: 'Ghaziabad'
Drawing on ax_gzb did not make it current. plt.title went to the current Axes, Faridabad's, and Ghaziabad's chart has no title at all. Nothing warned.
Each pyplot function has an Axes method that does the same on the Axes you name:
| pyplot (on the current Axes) | the Axes you hold |
|---|---|
plt.plot(x, y) | ax.plot(x, y) |
plt.title("...") | ax.set_title("...") |
plt.xlabel("..."), plt.ylabel("...") | ax.set_xlabel("..."), ax.set_ylabel("...") |
plt.xlim(0, 31) | ax.set_xlim(0, 31) |
plt.legend() | ax.legend() |
plt.grid(True) | ax.grid(True) |
pyplot's style is short for one quick chart. This lab writes ax because SaafHawa's reports make many charts, and ax.set_title can only ever title the chart it is called on. You keep plt for making figures (plt.subplots()); everything drawn goes through fig or ax.
A legend names the lines
A legend needs two steps. First, give each line a name when you draw it, with the argument label=. Then call ax.legend(), which collects every line that has a label and draws a small box with a sample of each line and its name:
fig, ax = plt.subplots()
ax.plot(days, ghaziabad, label="Ghaziabad")
ax.plot(days, faridabad, label="Faridabad")
ax.set_title("PM2.5 in December 2025")
ax.legend()
In [12]: ax.get_legend_handles_labels()
Out[12]:
([<matplotlib.lines.Line2D at 0xffffa832a710>,
<matplotlib.lines.Line2D at 0xffffa83aead0>],
['Ghaziabad', 'Faridabad'])
In [14]: [text.get_text() for text in ax.get_legend().get_texts()]
Out[14]: ['Ghaziabad', 'Faridabad']
<!-- chart: !The same two December lines, now with a legend in the upper right: blue is Ghaziabad, orange is Faridabad -->
ax.get_legend_handles_labels() is what ax.legend() will use: the labelled lines (the "handles") and their labels. The legend itself, once made, is ax.get_legend(), and its get_texts() are the Text objects it shows. Now the chart answers the question at a glance: Ghaziabad is above Faridabad on 30 of the 31 days, and its worst day, the 6th, was 295.4.
A line drawn without label= is left out of the legend. Inside, it has a label anyway, one that starts with an underscore, and the legend skips those:
In [6]: ax.get_legend_handles_labels()
Out[6]: ([<matplotlib.lines.Line2D at 0xffff7e729590>], ['Ghaziabad'])
In [7]: ax.get_lines()[1].get_label()
Out[7]: '_child1'
With no labelled line at all, ax.legend() still runs, draws an empty legend and warns you:
$ python3 no_labels.py
/workspace/chapters/02-inside-a-figure/no_labels.py:6: UserWarning: No artists with labels found to put in legend. Note that artists whose label start with an underscore are ignored when legend() is called with no argument.
ax.legend()
Where it sits. By default (loc="best") Matplotlib puts the legend in the corner where it covers the fewest points, so it can move when the data changes. loc= fixes it: "upper left", "upper right", "lower left", "lower right", "center" and a few more. frameon=False takes away the box around it, which on a clean chart is one line less for the eye.
A grid to read values against
ax.grid(True) draws faint lines across the chart at every tick, so a reader can follow a point across to its value on the axis. Two arguments make it quieter:
axis="y"draws only the y axis' grid, the horizontal lines. A line chart's value is read up the y axis, so lines going up from the x axis are mostly noise. (axis="x"is the other one;"both", the default, draws both.)alpha=is how see-through a line is, from 0 (invisible) to 1 (solid).alpha=0.3keeps the grid behind the data, where it belongs.
ax.legend(loc="lower left", frameon=False)
ax.grid(True, axis="y", alpha=0.3)
<!-- chart: !The December chart with a frameless legend at the lower left and faint horizontal grid lines at 50, 100, 150, 200, 250 and 300 -->
Call ax.grid once, with all three. Called without True, it switches the grid it names on if it was off and off if it was on, so a second call can undo the first:
In [4]: ax.grid(True)
In [5]: ax.grid(axis="y")
In [6]: fig.draw_without_rendering()
In [7]: ax.xaxis.get_gridlines()[0].get_visible()
Out[7]: True
In [8]: ax.yaxis.get_gridlines()[0].get_visible()
Out[8]: False
That chart has the grid the wrong way round: lines up from the x axis, none across. (The grid lines belong to each axis: ax.xaxis.get_gridlines() lists them, after the chart has been drawn once, which fig.draw_without_rendering() does without making a picture.)
Reading a chart back
Every set_ has a get_, and every Artist in the tree can be reached from the Figure. So a chart can tell you what it shows:
fig.axes[0]is its first Axes (here, its only one);ax.get_title(),ax.get_xlabel(),ax.get_ylabel()give the words,''when there are none;ax.get_lines()holds its lines, andlencounts them;ax.get_legend()is its Legend, or None when no legend was made.
In [9]: ax2.get_legend() is None
Out[9]: True
In [10]: ax2.get_title()
Out[10]: ''
A line that has a label is not a legend: get_legend_handles_labels() lists labelled lines whether or not anyone called ax.legend(), so to know what a reader sees, ask the legend itself. This is exactly how the Check reads your charts, and task 3 asks you to do the same.
Your turn
Four tasks, one file each. Task 1 draws two cities on one Axes with a legend that names each line; the Check also makes sure each name is beside its own city's line. Task 2 gives Ira's school chart a frameless legend in the upper left and a light grid on y only (watch the grid's toggle). Task 3 writes chart_facts(fig), a dict of a chart's title, labels, line count and legend words; one of the Check's charts has a labelled line and no legend. Task 4 is the interview question: Jaspreet's script titled the wrong chart, and Tanvir will ask which chart plt.title writes on and why ax.set_title cannot make that mistake. Try a function in ipython with from city_legend import city_lines; run the script with python3 two_charts.py and open delhi.png and noida.png in their tabs beside your code.
What you build: 4 tasks
Each task has tests. You write the code in the lab's editor and press Check.
- Task 1
city_legend.py: two cities and a legend
Write city_lines(days, pm_a, pm_b, city_a, city_b) in city_legend.py. days is a list of day numbers of one month (1, 2, 3, ...), pm_a and pm_b are two cities' daily PM2.5 on those days, from city_daily.csv, and city_a and city_b are the two cities' names. Make a new Figure and Axes, draw pm_a against days and pm_b against days as two lines on that one Axes, and add a legend whose two entries are exactly city_a and city_b.
It returns the Figure, with one Axes and exactly two lines. The Check also makes sure each name in the legend sits beside its own city's line: city_a beside the pm_a line, city_b beside the pm_b line. It tries Delhi and Gurugram over October 2025, and Noida and Faridabad over the first 10 days of November.
- Task 2
clean_look.py: a clean look for the schools
Write clean_look(days, pm25, city) in clean_look.py. days is a list of day numbers and pm25 a city's daily PM2.5 on those days, from city_daily.csv. Make a new Figure and Axes and draw pm25 against days as one line whose legend entry is exactly the city's name. Then:
the legend sits at the upper left (loc "upper left") and has no frame around it;
the chart has grid lines across it from the y axis only (no grid lines going up from the x axis), drawn at alpha 0.3.
It returns the Figure, with one Axes and one line. The Check tries Ghaziabad over November 2025 and Gurugram over the first 14 days of December, and reads the legend's place and frame and both axes' grid lines.
- Task 3
chart_facts.py: read a chart back
Write chart_facts(fig) in chart_facts.py. fig is a Figure with one Axes, made by the Check. Return a dict with exactly these five keys:
"title": the Axes' title, "" when it has none
"xlabel": its x axis label, "" when it has none
"ylabel": its y axis label, "" when it has none
"lines": how many lines it holds, a whole number (an int)
"legend": a list of the words in its legend, top to bottom, or [] when the chart has no legend
The Check gives it four charts: one with a title, both labels, two lines and a legend; one bare line with no words; three lines of which only two are in the legend; and one line that has a label but no legend on its chart, where "legend" is [].
- Task 4 · interview question
Interview: two_charts.py, the title on the wrong chart
Jaspreet's script makes two charts for the week's report and saves them as delhi.png and noida.png. noida.png is right, but delhi.png has no title and no y axis label. Fix the script so that each file holds its own city's chart:
delhi.png: a PNG with one chart and one line, Delhi's readings against the days, titled PM2.5 in Delhi, its y axis labelled with Y_LABEL (PM2.5 (µg/m³)).
noida.png: the same for Noida, titled PM2.5 in Noida, its y axis labelled with Y_LABEL.
Keep the lines days = [1, 2, 3, 4, 5, 6, 7], delhi = [...] and noida = [...] as they are: the Check runs the file again with them changed to days = [8, 9, 10], delhi = [139.7, 176.0, 214.5] and noida = [150.2, 181.9, 228.0], and reads what each figure held when it was saved. Fix it with the Axes' own methods: the file must call none of pyplot's drawing functions (plt.title, plt.xlabel, plt.ylabel, plt.plot, plt.legend, plt.grid, plt.gca, plt.gcf).
Tanvir will ask: which chart does plt.title write on, why did Delhi's title land on Noida's chart, and why can ax.set_title not make that mistake?
What you will learn
- The tree of Artists: a Figure holds Axes; an Axes holds its lines, texts, ax.xaxis and ax.yaxis, four ax.spines and a legend.
- pyplot's state: plt.title and plt.plot draw on the current Axes, plt.gca(), which is the last one made.
- label= and ax.legend(): name each line, then show the names; loc= and frameon=False.
- ax.grid(True, axis="y", alpha=0.3): faint lines to read values against.
- Reading a chart back: get_title, get_xlabel, get_ylabel, get_lines, get_legend().
More in The first chart
Build "Inside a figure" yourself
SaafHawa runs air sensors across Delhi NCR. Principals, societies and investors need its numbers at a glance: you draw them. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.
Free with a Google or GitHub sign-in, like the first 2 chapters of every lab.