🎓 A1Learner
🔍
0 of 50 lessons completed

Labelling and Saving a Chart

Labels tell the reader what a chart shows. A title names the chart, and each side gets its own label.

A title and side labels

The title names the chart. Each side label names its numbers.

import os
import matplotlib.pyplot as plt

x = [1, 2, 3]
y = [2, 1, 3]
plt.plot(x, y)
plt.title("Units sold")
plt.xlabel("Day")
plt.ylabel("Units")
plt.savefig("chart.png")
print(os.path.getsize("chart.png"))

A bigger chart

figsize sets the width and height in inches. This chart is eight inches wide and four high.

import os
import matplotlib.pyplot as plt

plt.figure(figsize=(8, 4))
plt.plot([1, 2, 3], [2, 1, 3])
plt.title("Units sold")
plt.savefig("chart.png")
print(os.path.getsize("chart.png"))

A legend for two lines

Each line carries a label. legend prints those labels in a small box.

import os
import matplotlib.pyplot as plt

plt.plot([1, 2, 3], [2, 1, 3], label="Tea")
plt.plot([1, 2, 3], [1, 2, 3], label="Coffee")
plt.legend()
plt.savefig("chart.png")
print(os.path.getsize("chart.png"))

Example

import io
import matplotlib.pyplot as plt
import os
import pandas as pd

SALES_CSV = """
order_id,date,product,category,units,price,region
101,2026-01-05,Tea,Drink,2,4.50,North
102,2026-01-06,Coffee,Drink,1,6.00,South
103,2026-01-07,Mug,Home,3,12.00,East
104,2026-01-08,Notebook,Office,2,8.50,West
105,2026-01-09,Pen,Office,5,2.00,North
106,2026-01-12,Lamp,Home,1,24.00,South
107,2026-01-13,Tea,Drink,4,4.50,East
108,2026-01-14,Coffee,Drink,2,6.00,West
109,2026-01-15,Mug,Home,1,12.00,North
110,2026-01-16,Notebook,Office,3,8.50,South
111,2026-01-19,Pen,Office,2,2.00,East
112,2026-01-20,Lamp,Home,2,24.00,West"""

sales = pd.read_csv(io.StringIO(SALES_CSV))
by_category = sales.groupby("category")["units"].sum()
print(by_category)
by_category.plot(kind="bar")
plt.title("Units sold by category")
plt.xlabel("Category")
plt.ylabel("Units")
plt.savefig("chart.png")
print(os.path.getsize("chart.png"))

Key points

  • Use plt.title to name the chart.
  • Use plt.xlabel and plt.ylabel to label each side.
  • Use plt.legend to show what each line means.
  • Use figsize to set the width and height of the chart.
  • A legend needs a label on each line it explains.

In this example, the sales table loads from its CSV text. groupby adds up the units for each category. The totals print first, then plot draws one bar per category. The title and side labels name the chart, and savefig writes it to chart.png. getsize prints the file size as proof.

Note

Add labels before savefig runs. Labels added after the save do not reach the file.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

Which call names the chart itself?