In this lesson you'll make your first real chart in Python, starting from two lists of numbers and finishing with a labelled, styled chart saved as an image you could put in a report. Each step adds one thing, so you can see exactly what each line of code does.
You need Python with Matplotlib installed. The quickest way is Google Colab, which has it ready with nothing to install; for a setup on your own computer, follow set up a machine learning environment in Python. If you've never used Python lists before, start with Python lists.
The data
We'll chart the average monthly maximum temperature in a city, in °C:
months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
temps = [22, 26, 32, 38, 41, 39, 34, 33, 33, 32, 28, 23]
These are rounded, typical values for a city in north India. The question our chart answers: how does temperature change through the year? That's change over time, so a line chart is the right choice, as explained in how to choose the right chart.
Step 1: import Matplotlib
import matplotlib.pyplot as plt
pyplot is the part of Matplotlib for making charts, and plt is the short name everyone uses.
Step 2: plot the line
plt.plot(months, temps)
plt.show()
That's a chart. plt.plot(x, y) takes the values for the horizontal axis first and the vertical axis second; they must have the same length. plt.show() displays it. (In Jupyter or Colab, charts appear even without plt.show(), but it's a good habit, and it's required in a normal .py script.)
You can already see the story: a steep climb to a May peak, a dip as the monsoon arrives, then cooling towards winter. But a reader wouldn't know what the numbers mean.
Step 3: add a title and axis labels
plt.plot(months, temps)
plt.title("Average maximum temperature by month")
plt.xlabel("Month")
plt.ylabel("Temperature (°C)")
plt.show()
Every chart you show anyone needs a title that says what it shows, and axis labels with units. It's the cheapest improvement you'll ever make.
Step 4: style the line
plot accepts options to change the look:
plt.plot(months, temps, color="darkorange", marker="o",
linewidth=2, markersize=6)
plt.title("Average maximum temperature by month")
plt.xlabel("Month")
plt.ylabel("Temperature (°C)")
plt.grid(alpha=0.3)
plt.show()
| Option | Does | Examples |
|---|---|---|
color | Line colour | "darkorange", "tab:blue", "#1f77b4" |
marker | A symbol at each point | "o" circle, "s" square, "^" triangle |
linestyle | Line pattern | "-" solid, "--" dashed, ":" dotted |
linewidth | Thickness | 2 |
markersize | Marker size | 6 |
Markers help readers see that the data is 12 separate months, not a continuous measurement. plt.grid(alpha=0.3) adds faint gridlines; alpha sets transparency, from 0 (invisible) to 1 (solid).
Step 5: compare two lines
Add the minimum temperatures, give each line a label, and call plt.legend() to show which is which:
mins = [8, 11, 16, 22, 27, 29, 27, 26, 25, 19, 13, 9]
plt.plot(months, temps, marker="o", color="darkorange", label="Maximum")
plt.plot(months, mins, marker="o", color="steelblue", label="Minimum")
plt.title("Average daily temperature range by month")
plt.xlabel("Month")
plt.ylabel("Temperature (°C)")
plt.legend()
plt.grid(alpha=0.3)
plt.show()
Each call to plt.plot adds another line to the same chart, until plt.show() displays it. Now there's a second insight: the gap between day and night is widest in spring and narrowest in the monsoon.
Step 6: save it as an image
Use plt.savefig before plt.show(). Showing a chart can clear it, so saving afterwards may give you a blank image:
plt.plot(months, temps, marker="o", color="darkorange", label="Maximum")
plt.plot(months, mins, marker="o", color="steelblue", label="Minimum")
plt.title("Average daily temperature range by month")
plt.xlabel("Month")
plt.ylabel("Temperature (°C)")
plt.legend()
plt.grid(alpha=0.3)
plt.savefig("temperature.png", dpi=200, bbox_inches="tight")
plt.show()
dpi=200makes a sharp, high-resolution image, good for reports and slides.bbox_inches="tight"trims empty space around the chart so labels aren't cut off.- Change the extension to
.svgor.pdffor an image that stays sharp at any size.
The file appears in the same folder as your script or notebook.
The complete program
import matplotlib.pyplot as plt
months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
temps = [22, 26, 32, 38, 41, 39, 34, 33, 33, 32, 28, 23]
mins = [8, 11, 16, 22, 27, 29, 27, 26, 25, 19, 13, 9]
plt.plot(months, temps, marker="o", color="darkorange", label="Maximum")
plt.plot(months, mins, marker="o", color="steelblue", label="Minimum")
plt.title("Average daily temperature range by month")
plt.xlabel("Month")
plt.ylabel("Temperature (°C)")
plt.legend()
plt.grid(alpha=0.3)
plt.savefig("temperature.png", dpi=200, bbox_inches="tight")
plt.show()
Common problems
| Problem | Cause | Fix |
|---|---|---|
ModuleNotFoundError: No module named 'matplotlib' | Not installed in this Python | pip install matplotlib in the same environment |
ValueError: x and y must have same first dimension | The two lists have different lengths | Check len(months) and len(temps) |
| No chart window appears in a script | Missing plt.show() | Add it at the end |
| The saved image is blank | savefig after show | Save first, then show |
| The legend is empty | No label= on the lines | Add label="..." to each plot |
Practice
- Plot these weekly study hours as a line chart with a title and axis labels: weeks 1 to 6, hours
[5, 7, 6, 9, 12, 10].
Show the answer
weeks = [1, 2, 3, 4, 5, 6]
hours = [5, 7, 6, 9, 12, 10]
plt.plot(weeks, hours, marker="o")
plt.title("Study hours per week")
plt.xlabel("Week")
plt.ylabel("Hours")
plt.show()
- Make the line dashed and green, with square markers.
Show the answer
plt.plot(weeks, hours, color="green", linestyle="--", marker="s")
plt.show()
- Save your chart as
study.svg. Why might you choose SVG instead of PNG?
Show the answer
plt.savefig("study.svg", bbox_inches="tight") before plt.show(). SVG is a vector format, so it stays perfectly sharp at any zoom level, which is ideal for websites and printed documents.
Interview questions
How do you create a basic line chart in Matplotlib?
Import matplotlib.pyplot as plt, call plt.plot(x, y), add plt.title, plt.xlabel and plt.ylabel, and call plt.show() to display it, or plt.savefig() before showing to save it.
Why should savefig be called before show?
plt.show() displays and then can close or clear the current figure, especially in scripts, so a later savefig may write an empty image.
What do dpi and bbox_inches="tight" do in savefig?
dpi sets the resolution in dots per inch, so a higher value means a sharper, larger image. bbox_inches="tight" crops the saved image to the chart's content, removing extra whitespace and preventing labels from being cut off.
What to learn next
- Name every part of a chart in anatomy of a chart: figure, axes, ticks and legends.
- Go deeper on lines in line plots with Matplotlib.