A First Chart
Matplotlib draws charts from numbers. A chart starts with points, and savefig writes the chart to a file.
A first chart
Three points join into one line. The file size proves the chart was saved.
import os
import matplotlib.pyplot as plt
x = [1, 2, 3]
y = [2, 1, 3]
plt.plot(x, y)
plt.savefig("chart.png")
print(os.path.getsize("chart.png"))
Points with markers
A marker draws a dot at each point. The line still joins them.
import os
import matplotlib.pyplot as plt
x = [1, 2, 3]
y = [2, 1, 3]
plt.plot(x, y, marker="o")
plt.savefig("chart.png")
print(os.path.getsize("chart.png"))
Two lines on one chart
A second plot call adds a second line. Both lines share the chart.
import os
import matplotlib.pyplot as plt
x = [1, 2, 3]
plt.plot(x, [2, 1, 3])
plt.plot(x, [3, 2, 1])
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))
orders = list(sales["order_id"])
units = list(sales["units"])
plt.plot(orders, units)
plt.savefig("chart.png")
print(os.path.getsize("chart.png"))
Key points
- Matplotlib is a library for drawing charts.
- Use plt.plot to draw points joined by a line.
- Use plt.savefig to write the chart to a file.
- Use os.path.getsize to check the file size and prove the file exists.
- The two lists in plt.plot hold the sideways positions and the heights.
In this example, the sales table loads from its CSV text. Order numbers become the sideways positions, and units become the heights. plt.plot draws one line across the twelve orders. savefig writes the chart to chart.png, and getsize prints the file size as proof.
Note
Save the chart before the program ends. A chart that is never saved is never a file.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
Which call writes a chart to a file?