Matplotlib · Chapter 1 of 16
Why charts, and your first figure
By the end of this chapter you can say why SaafHawa sends charts and not tables, say what a Matplotlib Figure and an Axes are, make both with fig, ax = plt.subplots(), draw a line with ax.plot, give it a title and axis labels, and save it as a PNG file with fig.savefig. 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
SaafHawa puts air sensors on the roofs of schools, housing societies and offices across Delhi NCR: 48 of them, each reading PM2.5 (the fine dust that gets deep into the lungs) every hour. That is 1,152 readings a day. Every morning Ira, the founder, sends each school a message about yesterday's air, because a principal decides from it whether the morning assembly and the games period happen outdoors.
Today the message is a table. Lalitha, who runs finance and operations, pastes a day's numbers into an email, and the replies come back the same way: "So was it bad? When was it better?" The numbers are right; nobody can read them fast enough. Jaspreet, the field engineer who climbs onto the roofs and keeps the sensors running, gets calls every week about a sensor "showing something odd" that turns out to be an ordinary evening.
Tanvir, SaafHawa's staff data scientist, is moving every report to Matplotlib, the library Python's charts are built on (pandas' .plot and most other plotting tools draw with it). You do it with him. You know Python, a little NumPy and a little pandas: you can load the readings and print them. This lab turns them into pictures people read at a glance.
The lesson
The same numbers, two ways
Here is Delhi's air, hour by hour, on 2 December 2025, the average of SaafHawa's Delhi sensors. The data is in /workspace/data; lab data lists the files.
import pandas as pd
hourly = pd.read_csv("/workspace/data/delhi_hourly.csv")
day = hourly[hourly["time"].str.startswith("2025-12-02")]
hours = list(range(24))
pm25 = day["pm25"].tolist()
print(pm25)
[153.4, 148.3, 142.9, 138.4, 134.7, 135.6, 130.7, 124.9, 116.0, 104.8, 99.8, 91.6, 83.7, 79.5, 79.7, 83.5, 89.1, 100.4, 112.4, 126.7, 138.8, 145.9, 151.2, 151.0]
A principal asks two questions: when was the air cleanest, and for how long did it stay under 90? Try to answer from the list. You have to read all 24 numbers, keep the smallest in your head, and count positions to turn each one back into an hour. The answer (cleanest at 1 pm, 79.5, and under 90 from noon to 4 pm) is in there, but finding it is work.
Now the same 24 numbers as a line:
<!-- chart: !Delhi's PM2.5 on 2 December 2025, high at night, falling to a low around 1 pm, rising again in the evening -->
The shape answers both questions before you read a single number: high all night, a deep dip in the early afternoon, back up by evening. A chart does not hold more than the list; it puts the numbers where your eyes compare them for you.
A Figure and its Axes
Matplotlib's main module for making charts is matplotlib.pyplot, always imported as plt. Its function plt.subplots() makes a new chart and gives you two objects. Try it in IPython, the friendlier Python shell in your lab (type ipython in the terminal):
In [1]: import matplotlib.pyplot as plt
In [2]: fig, ax = plt.subplots()
In [3]: fig
Out[3]: <Figure size 640x480 with 1 Axes>
In [4]: ax
Out[4]: <Axes: >
In [5]: fig.axes
Out[5]: [<Axes: >]
In [6]: fig.get_size_inches()
Out[6]: array([6.4, 4.8])
In [7]: fig.dpi
Out[7]: 100.0
- The Figure (
fig) is the whole picture: the canvas everything is drawn on, with a size (6.4 by 4.8 inches) and a resolution (100 dots per inch, so 640 by 480 pixels). It is what you save to a file. - An Axes (
ax) is one chart inside the Figure: the box with an x axis and a y axis, and everything drawn in it, its lines, its title, its labels.fig.axesis the list of the charts in the Figure; here there is one.
The name trips everyone up: an Axes is a whole chart, and it has two axis objects (the x axis and the y axis). A Figure can hold several Axes side by side; chapter 12 does that. plt.subplots() with nothing in the brackets makes a Figure with one Axes and gives you both at once, as a tuple that fig, ax = unpacks.
Drawing a line
ax.plot(x, y) draws a line through the points (x[0], y[0]), (x[1], y[1]) and so on, in order. It gives back a list of the lines it drew, and the Axes keeps them:
In [1]: import matplotlib.pyplot as plt
In [2]: hours = [10, 11, 12, 13, 14]
In [3]: pm25 = [99.8, 91.6, 83.7, 79.5, 79.7]
In [4]: fig, ax = plt.subplots()
In [5]: lines = ax.plot(hours, pm25)
In [6]: lines
Out[6]: [<matplotlib.lines.Line2D at 0xffffa4b84410>]
In [7]: ax.get_lines()
Out[7]: <a list of 1 Line2D objects>
In [8]: line = ax.get_lines()[0]
In [9]: line.get_xdata()
Out[9]: array([10, 11, 12, 13, 14])
In [10]: line.get_ydata()
Out[10]: array([99.8, 91.6, 83.7, 79.5, 79.7])
A Line2D is the line itself, and it remembers its data as NumPy arrays. (The 0xffff... is where it sits in memory, different every run.) Everything Matplotlib draws is an object like this one, which is how this lab's Check reads your charts without looking at a single pixel.
x comes first, then y. The two must be the same length, one x for every y; one reading short and Matplotlib refuses (the last line of the error):
ValueError: x and y must have same first dimension, but have shapes (5,) and (4,)
Give plot only one list and it uses that list as y, with x counting from 0, which is right only when your x really starts at 0:
In [3]: line, = ax.plot([99.8, 91.6, 83.7, 79.5, 79.7])
In [4]: line.get_xdata()
Out[4]: array([0., 1., 2., 3., 4.])
Those readings were taken at 10 am to 2 pm, not at hours 0 to 4. Pass the hours.
Saying what it shows
A bare line is a shape with no meaning: what is going up, measured in what, over what? Three methods of the Axes add the words, and the Axes shows them when you look at it:
fig, ax = plt.subplots()
ax.plot(hours, pm25)
ax.set_title("Delhi, late morning")
ax.set_xlabel("Hour")
ax.set_ylabel("PM2.5 (µg/m³)")
In [14]: ax
Out[14]: <Axes: title={'center': 'Delhi, late morning'}, xlabel='Hour', ylabel='PM2.5 (µg/m³)'>
In [15]: ax.get_title()
Out[15]: 'Delhi, late morning'
The title says what the chart is about, each label says what its axis measures and in which unit (µg/m³ is micrograms of dust in a cubic metre of air). Every set_ method has a get_ partner that reads the value back.
The mistake everyone makes once: ax.title is not a method you call, it is the title's text object, so
In [3]: ax.title("PM2.5 in Delhi")
TypeError: 'Text' object is not callable
The method is ax.set_title(...).
Saving it to a file
Your lab is a Linux machine with no screen, so Matplotlib draws with Agg, a backend that renders charts into image files instead of windows:
In [2]: plt.get_backend()
Out[2]: 'Agg'
plt.show(), which opens a window on a laptop, does nothing here and says nothing. So the way to see a chart is to save it. fig.savefig(name) writes the whole Figure to a file, and the name's ending picks the format: .png is a PNG image. Here is the whole program for the chart at the top of this chapter:
import matplotlib.pyplot as plt
import pandas as pd
hourly = pd.read_csv("/workspace/data/delhi_hourly.csv")
day = hourly[hourly["time"].str.startswith("2025-12-02")]
hours = list(range(24))
pm25 = day["pm25"].tolist()
fig, ax = plt.subplots()
ax.plot(hours, pm25)
ax.set_title("PM2.5 in Delhi, 2 December 2025")
ax.set_xlabel("Hour of the day")
ax.set_ylabel("PM2.5 (µg/m³)")
fig.savefig("delhi_2_dec.png")
$ python3 first_look.py
$ lab image delhi_2_dec.png
delhi_2_dec.png: PNG, 640 x 480 pixels, 100 dpi, 29.1 KB
The file lands in the folder you ran the program from (the chapter's folder), at the Figure's size: 6.4 inches at 100 dots per inch is 640 pixels across. Chapter 3 changes the size, the resolution and the format.
savefig saves what the Figure holds at that moment. Saved before the line is drawn, the file is an empty chart, and nothing warns you:
In [5]: fig.savefig("too_early.png")
In [6]: ax.plot([10, 11, 12], [99.8, 91.6, 83.7])
Out[6]: [<matplotlib.lines.Line2D at 0xffff76fb6d50>]
$ lab image too_early.png delhi_2_dec.png
too_early.png: PNG, 640 x 480 pixels, 100 dpi, 8.9 KB
delhi_2_dec.png: PNG, 640 x 480 pixels, 100 dpi, 29.1 KB
Same size in pixels, a third of the bytes: it holds an empty box. Draw everything first, save last.
Every chart is its own Figure
Each call of plt.subplots() makes a new Figure with a new, empty Axes. Each call of ax.plot adds a line to the Axes it is called on, next to whatever is there already. Both facts are useful, and together they decide what ends up on which chart:
fig, ax = plt.subplots()
ax.plot(hours, nov)
ax.plot(hours, dec)
print(len(ax.get_lines()))
fig2, ax2 = plt.subplots()
ax2.plot(hours, dec)
print(len(ax2.get_lines()), len(ax.get_lines()))
print(fig is fig2)
2
1 2
False
Two plots on one Axes put 3 November and 2 December on one chart, which is how you compare two days (chapter 2 adds the legend that says which line is which). The second plt.subplots() made a second Figure, and drawing on it left the first one alone.
<!-- chart: !Two days on one Axes: 3 November far above 2 December all day -->
Your turn
Four tasks, one file each. Task 1 draws Jaspreet's school-day readings and saves them as first_chart.png; the Check runs it with other readings too, so draw the lists, not numbers typed in. Task 2 gives a chart its title and both labels, word for word. Task 3 saves a week's chart at the path it is given; the Check looks at what the figure held when it was saved. Task 4 is the interview question: Ira's function put Dwarka's line on Saket's chart, and Tanvir will ask what a Figure and an Axes are, and why. Run a program with python3 first_chart.py and look at its file with lab image first_chart.png; try a function in ipython with from labelled import pm_chart.
What you build: 4 tasks
Each task has tests. You write the code in the lab's editor and press Check.
- Task 1
first_chart.py: your first chart
Jaspreet's sensor on the roof of a school in Dwarka read PM2.5 every hour of the school day, 7 am to 2 pm, on 17 October 2025. The starter keeps the hours and the readings in two lines, hours = [7, 8, 9, 10, 11, 12, 13, 14] and pm25 = [65.6, 63.0, 61.1, 61.4, 59.4, 57.1, 56.6, 60.4]. Keep both lines as they are. Below them, make a Figure and its one Axes with plt.subplots(), draw pm25 against hours as a line on that Axes, and save the figure as first_chart.png in this folder.
The Check runs the file and reads the figure it saved: first_chart.png must be a PNG, and the figure in it must have exactly one Axes with exactly one line, the hours along x and the readings up y. It runs the file again with the two lines changed to hours = [6, 7, 8, 9] and pm25 = [88.2, 97.5, 104.1, 99.0], so draw the two lists themselves, never numbers typed in again.
- Task 2
labelled.py: say what the chart shows
Write pm_chart(hours, pm25, place) in labelled.py. It makes a new Figure and Axes, draws pm25 against hours as one line, and gives the chart a title, an x axis label and a y axis label, exactly:
title: PM2.5 at <place>, the words PM2.5 at, a space, then the place it is given (pm_chart(hours, pm25, "Saket") is titled PM2.5 at Saket)
x axis label: Hour (IST)
y axis label: PM2.5 (µg/m³), which the starter keeps in Y_LABEL
It returns the Figure (fig itself, not the Axes and not a tuple), with exactly one Axes and one line. The Check calls it with Saket's 24 readings of 24 October 2025 and Rohini Sector 9's readings from 6 am to noon on 25 October, and checks the line, the title and both labels, word for word.
- Task 3
save_chart.py: save the week's chart
Write save_chart(days, pm25, path) in save_chart.py. days is a list of day numbers (14 to 20 for 14 to 20 October) and pm25 the sensor's daily PM2.5 for each. It makes a new Figure and Axes, draws pm25 against days as one line, titles the chart PM2.5, day by day (exactly), saves the figure as a PNG at path, and returns the Figure.
The file must be 640 by 480 pixels, the size a new figure has: change nothing about its size or resolution. The Check gives paths in another folder, ending in mayur_vihar.png and punjabi bagh week.png, so save at the path it is given. It also looks at what the figure held at the moment it was saved: the line and the title must be on it by then, and the figure returned must be the one saved.
- Task 4 · interview question
Interview: two_schools.py, one chart per school
Ira's school_chart(hours, pm25, school) draws one school's hourly readings as a line titled with the school's name, and returns the Figure. The first chart of the morning is right; the second is not: Saket's chart shows Dwarka's line as well, under Saket's title, and the Figure returned for Dwarka has changed too. Fix it so that every call returns a Figure of its own with one Axes, one line (that school's readings, hours along x) and the school's name as its title, however many times it is called.
The Check imports the file once and calls school_chart for Dwarka and then for Saket (their readings from 6 am to 6 pm on 22 October 2025), then checks Saket's chart and Dwarka's again: two different Figures, each with its own one line and title.
Tanvir will ask: what is a Figure, what is an Axes, and why did Saket's chart show Dwarka's line?
What you will learn
- Why charts: the same 24 numbers as a list and as a line.
- A Figure and an Axes: the whole picture, and one chart inside it.
- plt.subplots(): makes a Figure and its Axes, and gives you both.
- ax.plot(x, y): draws a line through the points.
- ax.set_title, ax.set_xlabel, ax.set_ylabel: say what the chart shows.
- fig.savefig("chart.png"): writes the chart to a file.
More in The first chart
Build "Why charts, and your first 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.