SyntaxPilot
Courses/Data Analytics with Python/Lesson 30
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

Data Analytics with Python · Lesson 30 of 90

Charts 1: matplotlib basics

matplotlibpyplotfigureaxesobject-oriented API vs pyplot APIplotline chartbar chartbarhtitlexlabelylabellegendgrid

These are the notes for Data Analytics with Python, episode 30. For 29 episodes we printed tables. A chart turns a column of numbers into a shape your eyes understand in a second. Here you invent the parts of a chart one problem at a time: matplotlib and pyplot, plot and the line chart, why plt.show() can show nothing and what savefig does, title, xlabel, ylabel, legend and grid, the figure and axes, the pyplot API vs the object-oriented API, the bar chart and barh, and dpi. Every term is defined the first time it appears and collected in the Glossary. Every program below was run for real (Python 3.13, matplotlib 3.11.2, on a server with no screen); the images are the files those exact programs saved. The numbers are made up for teaching.

Why charts

Ramesh brings the owner a table: cups sold each month, January to June, for the Pune and Nashik stalls. Twelve numbers. Is Pune growing? Which month was best? The owner has to compare digits one by one. Drawn as a line, the answer jumps out: up, up, up, a peak in May, a dip in June.

matplotlib and pyplot

  • matplotlib is Python's classic charting library. pandas' .plot() and seaborn (episode 33) draw with it behind the scenes. A library is code someone else wrote that you import.
  • pyplot is its easy front door, a module everyone imports as plt: import matplotlib.pyplot as plt.
  • plt.plot(x, y) puts a point for each (x, y) pair and joins them in order. x gives positions along the bottom (the months), y the heights (the cups). Points joined in order make a line chart, the best chart for a trend over time.

Every program starts with these lines:

import sys; sys.tracebacklimit = 0
import matplotlib.pyplot as plt
months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"]
pune = [7900, 8800, 9400, 10100, 11800, 9900]
nashik = [5200, 5600, 6100, 6000, 6900, 6400]

show vs savefig

The obvious attempt: plot, then plt.show(), which normally opens a window with the chart.

plt.plot(months, pune)
plt.show()
print("done?")
done?

No chart, no error. Why: show draws on a screen. This program runs on a server with no screen, so matplotlib picks a backend (the part of matplotlib that turns a chart into pixels or a window) called Agg that draws only into memory, and show has nowhere to put the picture. In Jupyter or Colab (episode 3), charts appear under the cell automatically; on a laptop with a screen, show opens a window.

The fix: plt.savefig("name.png") writes the chart to an image file. PNG is a lossless image format, good for charts (sharp lines and text).

plt.plot(months, pune)
plt.savefig("line1.png")
print("saved line1.png")
saved line1.png

line1.png

The months sit along the bottom, the x axis; the numbers run up the side, the y axis. Each mark with a number on an axis is a tick. But what is this? Cups? Rupees? Which stall? A chart without words is a puzzle.

Titles, labels and markers

plt.plot(months, pune, marker="o")
plt.title("Pune stall: cups sold per month")
plt.xlabel("Month")
plt.ylabel("Cups sold")
plt.savefig("line2.png")
print("saved line2.png")
saved line2.png

line2.png

  • plt.title: a heading above the chart.
  • plt.xlabel / plt.ylabel: names for the x and y axes (include the unit if there is one).
  • marker="o": draws a dot on each real data point ("s" = square, "^" = triangle), so readers see where the measurements are and that the line between them is only a guide.

Every chart you share needs at least a title and axis labels.

Two lines: legend and grid

Calling plot twice draws both lines on the same chart:

plt.plot(months, pune)
plt.plot(months, nashik)
plt.title("Cups sold per month")
plt.savefig("line3.png")
print("saved line3.png")
saved line3.png

line3.png

Which line is Pune? matplotlib picked the colours (blue first, then orange) and nothing says what they mean. The fix: give each line a label= and call plt.legend(). A legend is the key that matches each colour/marker to its name, like the key on a map. plt.grid(True, alpha=0.3) adds faint guide lines so values can be read off the chart; alpha is transparency, from 0 (invisible) to 1 (solid).

plt.plot(months, pune, marker="o", label="Pune")
plt.plot(months, nashik, marker="s", label="Nashik")
plt.title("Cups sold per month")
plt.xlabel("Month")
plt.ylabel("Cups sold")
plt.legend()
plt.grid(True, alpha=0.3)
plt.savefig("line4.png")
print("saved line4.png")
saved line4.png

line4.png

Figure and axes

Behind the scenes a chart is made of two objects. Real-life picture: a photo frame on a wall.

On a wall In matplotlib What it holds
The frame Figure the whole image: its size, the file you save
A photo in the frame Axes one chart: its lines, title, axis labels, ticks

A frame can hold one photo or several, and a figure can hold one axes or several (episode 31). Axes is not the plural of axis: one Axes object has an x axis and a y axis.

The pyplot API vs the object-oriented API

An API (application programming interface) is the set of commands a library offers you. matplotlib has two styles:

  • pyplot API (plt.plot, plt.title, …): short to type; every command draws on the current axes, which matplotlib tracks for you. Fine for one quick chart.
  • Object-oriented (OO) API: fig, ax = plt.subplots() creates a Figure and an Axes and gives you names for both. Then you call methods on them: ax.plot, ax.set_title, ax.set_xlabel, ax.set_ylabel, ax.legend, fig.savefig. Explicit about which chart you mean, so professionals use it for anything with more than one chart.

figsize=(8, 4.5) sets the figure size in inches (width, height).

fig, ax = plt.subplots(figsize=(8, 4.5))
ax.plot(months, pune, marker="o", label="Pune")
ax.plot(months, nashik, marker="s", label="Nashik")
ax.set_title("Cups sold per month")
ax.set_xlabel("Month")
ax.set_ylabel("Cups sold")
ax.legend()
ax.grid(True, alpha=0.3)
fig.savefig("oo.png")
print(type(fig).__name__, type(ax).__name__)
Figure Axes

The same picture as before, now made the OO way:

oo.png

pyplot API OO API
plt.plot(x, y) ax.plot(x, y)
plt.title("…") ax.set_title("…")
plt.xlabel("…") / plt.ylabel("…") ax.set_xlabel("…") / ax.set_ylabel("…")
plt.legend() / plt.grid() ax.legend() / ax.grid()
plt.savefig("f.png") fig.savefig("f.png")
— ax.set(title=…, xlabel=…, ylabel=…) sets several at once

The classic mistake when switching styles:

fig, ax = plt.subplots()
ax.plot(months, pune)
ax.title("Cups sold per month")
TypeError: 'Text' object is not callable

On an Axes, title is the title text object itself, not a function, so calling it fails. Use ax.set_title(...).

Bar charts

New question: which stall sold the most from January to June? The bar programs start with:

stalls = ["Pune Station", "Nashik Road", "Mumbai Central", "Chennai Egmore", "Howrah Junction"]
totals = [57900, 36200, 81400, 44800, 52300]

The obvious attempt with the chart we know, a line:

fig, ax = plt.subplots()
ax.plot(stalls, totals, marker="o")
ax.set_title("Cups sold by stall, Jan-Jun")
fig.savefig("stalls_line.png")
print("saved stalls_line.png")
saved stalls_line.png

stalls_line.png

It looks like sales "crashed" at Nashik Road and "soared" at Mumbai Central. But stalls are not moments in time: there is nothing between them, and their order is just the order we typed. A line between categories (separate groups with no natural order in time) invents a trend that does not exist.

A bar chart draws one bar per category, with height = value, so the eye compares sizes. ax.bar(categories, values):

fig, ax = plt.subplots()
ax.bar(stalls, totals)
ax.set_title("Cups sold by stall, Jan-Jun")
ax.set_ylabel("Cups sold")
fig.savefig("stalls_bar.png")
print("saved stalls_bar.png")
saved stalls_bar.png

stalls_bar.png

Mumbai Central wins clearly, but the long names collide at the bottom. The fix: a horizontal bar chart, ax.barh, gives each name its own line. ax.invert_yaxis() puts the first category at the top (barh draws the first one at the bottom by default), and bbox_inches="tight" trims empty border space and makes sure no label is cut off when saving.

fig, ax = plt.subplots(figsize=(8, 4.5))
ax.barh(stalls, totals, color="tab:orange")
ax.set_title("Cups sold by stall, Jan-Jun")
ax.set_xlabel("Cups sold")
ax.invert_yaxis()
fig.savefig("stalls_barh.png", bbox_inches="tight")
print("saved stalls_barh.png")
saved stalls_barh.png

stalls_barh.png

Rule of thumb: time → line chart, categories → bar chart, long category names → horizontal bars. Bars should start at 0, because their length is the message (episode 32 covers misleading charts).

dpi and sharp images

Pasted into a slide, a chart can look blurry. The size of a saved image in pixels is:

pixels = figsize (inches) × dpi

dpi (dots per inch) is how many pixels are used for each inch of the figure. The default is 100.

fig, ax = plt.subplots(figsize=(8, 4.5))
ax.plot(months, pune, marker="o")
ax.set_title("Pune stall: cups sold per month")
fig.savefig("low.png", dpi=50)
fig.savefig("high.png", dpi=200)
print("low: ", plt.imread("low.png").shape)
print("high:", plt.imread("high.png").shape)
low:  (225, 400, 4)
high: (900, 1600, 4)

plt.imread reads an image back as an array of shape (height, width, channels). Low: 4.5 × 50 = 225 by 8 × 50 = 400 pixels. High: 900 by 1600. The 4 channels are red, green, blue and alpha (transparency).

dpi=50 (400 × 225 px) dpi=200 (1600 × 900 px)
low.png high.png

Enlarged to the same size, the low-dpi image is soft and blurry. For slides and reports, save at 150–200 dpi; for print, 300.

A real error: x and y lengths

plt.plot(months + ["Jul"], pune)
ValueError: x and y must have same first dimension, but have shapes (7,) and (6,)

Seven months, six values. Every x needs exactly one y. (shapes (7,) and (6,) are NumPy array shapes: 7 elements and 6 elements.)

Mini project: sales_chart()

A function that makes a report-ready chart every time: one labelled line per series, title and labels set in one call with ax.set, legend, light grid, saved at dpi 200 with a tight bounding box. plt.close(fig) releases the figure's memory, important when a script makes hundreds of charts (matplotlib warns after 20 open figures).

def sales_chart(months, series, title, filename):
    fig, ax = plt.subplots(figsize=(8, 4.5))
    for name, values in series.items():
        ax.plot(months, values, marker="o", label=name)
    ax.set(title=title, xlabel="Month", ylabel="Cups sold")
    ax.legend()
    ax.grid(True, alpha=0.3)
    fig.savefig(filename, dpi=200, bbox_inches="tight")
    plt.close(fig)
    return filename
print(sales_chart(months, {"Pune": pune, "Nashik": nashik},
                  "Cups sold per month, Jan-Jun", "report.png"))
report.png

report.png

Pune grows to a May peak and dips in June; Nashik grows slowly. The owner understands it in one second.

Common mistakes

Code / habit Real error / symptom Why Fix
plt.show() in a script on a server no error; no chart no screen to draw on (Agg backend) plt.savefig("chart.png")
ax.title("…") TypeError: 'Text' object is not callable on an Axes, title is an object ax.set_title("…")
plt.plot(months + ["Jul"], pune) ValueError: x and y must have same first dimension, but have shapes (7,) and (6,) one y for every x same-length lists
ax.plot(stalls, totals) no error; a fake trend categories are not time ax.bar / ax.barh
chart without title/labels/legend no error; nobody understands it missing words set_title, set_xlabel, set_ylabel, label= + legend()
saving at default dpi for slides blurry image 640 × 480 px stretched dpi=150–200
labels cut off in the file missing text at edges figure border too tight bbox_inches="tight"
making many charts in a loop RuntimeWarning: More than 20 figures have been opened figures stay in memory plt.close(fig)

Practice

1. Draw a labelled line chart of your steps this week (title, axis labels, markers, light grid), saved at dpi 150.

Solution
import sys; sys.tracebacklimit = 0
import matplotlib.pyplot as plt
days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
steps = [6200, 7400, 5100, 8000, 6900, 11200, 9800]
fig, ax = plt.subplots(figsize=(8, 4.5))
ax.plot(days, steps, marker="o")
ax.set_title("My steps this week")
ax.set_xlabel("Day")
ax.set_ylabel("Steps")
ax.grid(True, alpha=0.3)
fig.savefig("p1.png", dpi=150, bbox_inches="tight")
print("saved p1.png")
saved p1.png

2. A horizontal bar chart of daily screen time per activity, with each bar's value written at its end.

Solution
apps = ["Chat apps", "Video streaming", "Online classes", "Games"]
minutes = [95, 140, 120, 45]
fig, ax = plt.subplots(figsize=(8, 4.5))
bars = ax.barh(apps, minutes)
ax.bar_label(bars)
ax.set_title("Screen time per day (minutes)")
ax.invert_yaxis()
fig.savefig("p2.png", dpi=150, bbox_inches="tight")
print("saved p2.png")
saved p2.png

ax.bar_label(bars) writes each bar's value next to it (bar/barh return the bars so you can label them).

3. This week vs last week on one chart: a solid green line and a dashed grey line, with a legend.

Solution
fig, ax = plt.subplots(figsize=(8, 4.5))
ax.plot(days, steps, color="tab:green", linestyle="-", marker="o", label="This week")
ax.plot(days, [5000, 6800, 6100, 7000, 6400, 9000, 8800], color="gray", linestyle="--", label="Last week")
ax.set(title="Steps: this week vs last week", xlabel="Day", ylabel="Steps")
ax.legend()
fig.savefig("p3.png", dpi=150, bbox_inches="tight")
print("saved p3.png")
saved p3.png

color= picks a colour by name; linestyle="--" makes a dashed line (":" dotted, "-." dash-dot).

4. Fix this code: fig, ax = plt.subplots(); ax.plot(days, steps); ax.xlabel("Day").

Solution

On an Axes the method is ax.set_xlabel("Day"); ax.xlabel does not exist (it raises AttributeError: 'Axes' object has no attribute 'xlabel'). Only plt.xlabel exists in the pyplot API.

5. What pixel size does fig, ax = plt.subplots(figsize=(10, 5)); fig.savefig("p5.png", dpi=120) produce?

Solution
fig, ax = plt.subplots(figsize=(10, 5))
fig.savefig("p5.png", dpi=120)
print(plt.imread("p5.png").shape)
(600, 1200, 4)

10 × 120 = 1200 pixels wide, 5 × 120 = 600 high.

Quick quiz

fig, ax = plt.subplots(figsize=(6, 4))
ax.plot([1, 2, 3], [4, 5, 6])
fig.savefig("q.png", dpi=150)

How many pixels wide is q.png? A. 600 B. 900 C. 150 D. 6

Answer

B. 900. Width in pixels = 6 inches × 150 dpi. The height is 4 × 150 = 600.

Interview questions

  1. Figure vs Axes? The Figure is the whole canvas/image; an Axes is one plotting area with its own x and y axis. A figure can contain many axes.
  2. pyplot API vs object-oriented API? pyplot acts on the "current" axes implicitly; the OO API calls methods on explicit fig/ax objects, which is clearer with several charts.
  3. Why might plt.show() show nothing? A non-interactive backend (no display, e.g. on a server); save with savefig.
  4. When do you use a line chart vs a bar chart? Line for ordered/continuous data such as time; bars for comparing categories.
  5. Why use barh? Long category names stay readable, and ranked lists read top to bottom.
  6. How do you control image resolution? dpi in savefig; pixels = figsize × dpi.
  7. What does bbox_inches="tight" do? Crops the saved image to the drawn content so labels aren't cut off.
  8. Why call plt.close(fig)? To free memory when generating many figures in a loop.
  9. How do you label multiple lines? label= on each plot call, then legend().
  10. What does the error "x and y must have same first dimension" mean? The x and y sequences have different lengths.

Glossary

Term Meaning Example
Chart A picture of data a line of monthly cups
matplotlib Python's classic charting library import matplotlib
pyplot (plt) matplotlib's easy-to-use module import matplotlib.pyplot as plt
Library Reusable code you import matplotlib, pandas
plot Draws points joined by lines plt.plot(months, pune)
Line chart Values joined in order; shows trends over time cups per month
x axis / y axis Horizontal / vertical scale of a chart months / cups
Tick A marked position with a label on an axis "Jan", 8000
show Displays the chart on a screen nothing on a server
Backend The part that renders a chart (window, file, memory) Agg
savefig Writes the figure to an image file savefig("line1.png")
PNG Lossless image format, good for charts report.png
title / set_title Heading above a chart "Cups sold per month"
xlabel / ylabel Axis names "Month", "Cups sold"
Marker A symbol at each data point marker="o"
Legend Key matching colours/markers to names Pune, Nashik
label= The name a line shows in the legend label="Pune"
Grid Faint guide lines across the chart grid(True, alpha=0.3)
Alpha Transparency from 0 (invisible) to 1 (solid) alpha=0.3
Figure The whole image/canvas fig
Axes One chart area inside a figure ax
API The set of commands a library offers pyplot API
pyplot API plt.* commands acting on the current axes plt.title
Object-oriented API Methods on explicit fig/ax objects ax.set_title
plt.subplots() Creates a figure and axes fig, ax = plt.subplots()
figsize Figure size in inches (width, height) (8, 4.5)
Category (in charts) A separate group with no time order a stall
Bar chart One bar per category, height = value ax.bar
Horizontal bar chart Bars running sideways ax.barh
invert_yaxis Flips the y axis (first bar on top) ranked lists
bar_label Writes values on bars practice 2
dpi Dots (pixels) per inch when saving dpi=200
Pixel One dot of an image 1600 × 900
Channel One colour component of a pixel (R, G, B, alpha) 4 channels
bbox_inches="tight" Crop the saved image to its content no cut-off labels
plt.close Frees a figure's memory in loops

Summary

  • matplotlib draws charts; pyplot (plt) is its front door; plot(x, y) makes a line chart for trends over time.
  • With no screen, show shows nothing: savefig writes a PNG.
  • Every chart needs a title and axis labels, markers for real points, and a legend (with label=) when there is more than one line; a light grid helps reading.
  • A Figure is the frame, an Axes is one chart. The OO API (fig, ax = plt.subplots(), ax.set_title) names them explicitly.
  • Time → line, categories → bar, long names → barh.
  • pixels = figsize × dpi; save at 150–200 dpi with bbox_inches="tight".
  • Next episode: histograms, scatter plots, box plots and subplots.