Data Visualization with matplotlib¶
By the end of this lesson you'll be able to:
- Import and use matplotlib.pyplot to create charts in Python
- Add titles, axis labels, legends, and grids to any chart
- Create line plots, scatter plots, bar charts, and histograms
- Plot multiple lines on one chart and arrange subplots side by side
- Save a chart to an image file with
savefig()
A chart can communicate in one second what a table of numbers takes minutes to understand. matplotlib is the tool Python programmers reach for first.
Welcome to Chapter 32!
Data visualization turns raw numbers into stories you can see.
Scientists, journalists, business analysts, and game developers all use charts built with matplotlib.
Let's start plotting! Let's code it together!
Importing matplotlib¶
matplotlib is a large library — you typically import just its pyplot sub-module, aliased as plt:
1 | |
Everything you need — plt.plot(), plt.show(), plt.title() — lives in pyplot.
matplotlib in Skulpt
The Skulpt labs below use a text-based simulation to show the data that matplotlib would chart.
In a real Python environment (Thonny, VS Code, Jupyter), plt.show() opens an interactive window.
The patterns you learn here transfer directly — same function names, same parameters.
Your First Line Chart¶
plt.plot(x_values, y_values) draws a line connecting the given data points.
plt.show() renders the chart.
The simplest pattern is:
1 2 3 4 5 6 7 8 9 10 | |
Adding Labels, Titles, and a Grid¶
These functions dress up any chart:
| Function | Effect |
|---|---|
plt.title("text") |
Chart title |
plt.xlabel("text") |
Label the x-axis |
plt.ylabel("text") |
Label the y-axis |
plt.legend() |
Show a legend for labeled series |
plt.grid(True) |
Add a background grid |
plt.xlim(lo, hi) |
Set x-axis range |
plt.ylim(lo, hi) |
Set y-axis range |
Call them after plt.plot() but before plt.show().
Plotting Multiple Lines¶
Calling plt.plot() multiple times before plt.show() puts all lines on the same chart.
Use the label= parameter and then call plt.legend() so readers know which line is which.
What Do You Think Will Happen?
The code below plots three different mathematical series on one chart.
Which one do you think will grow fastest: x, x squared, or x cubed (scaled down)?
Make your guess — then run it!
Scatter Plots¶
A scatter plot shows individual data points without connecting them with lines.
Use plt.scatter(x, y) instead of plt.plot().
Scatter plots are ideal for showing relationships between two variables — for example, height vs. weight, or study hours vs. test score.
1 2 3 4 5 6 7 8 9 10 11 | |
The s= parameter controls dot size (default is 20).
The color= parameter accepts color names ("red", "blue", "green") or hex codes ("#FF6600").
Bar Charts¶
plt.bar(x_labels, heights) creates a vertical bar chart.
Bar charts are best for comparing discrete categories — scores by student, revenue by month, etc.
plt.grid(axis="y") adds grid lines only on the y-axis — a common style for bar charts.
Histograms¶
A histogram shows the distribution of a set of numbers — how many values fall in each range (called a "bin").
plt.hist(data, bins=10) automatically divides the data into bins equal-width groups and draws bars showing the count in each group.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | |
Saving Figures with savefig()¶
Instead of plt.show(), call plt.savefig("filename.png") to save the chart to a file.
1 2 3 | |
Supported formats include .png, .jpg, .pdf, and .svg.
Call savefig() before plt.show() — show() resets the figure.
Subplots — Multiple Charts Side by Side¶
plt.subplots(rows, cols) creates a grid of charts (called axes).
It returns the fig (the whole canvas) and an array of ax objects — one per chart position.
1 2 3 4 5 6 7 8 9 10 | |
Notice: when using subplots, use ax.set_title() (not plt.title()) and ax.set_xlabel() (not plt.xlabel()).
Learning Check¶
Your Turn — Fix the Bar Chart
The code below tries to make a bar chart but is missing the axis labels and title.
Add plt.title(), plt.xlabel(), and plt.ylabel() to complete it!
Experiments¶
Try these changes. Predict what will happen first, then run it to check!
-
Change the line chart colors by adding the
color=parameter:plt.plot(x, y, color="red"). You'll know it worked when the line appears in the color you chose. -
Add a
marker="o"parameter toplt.plot()to show dots at each data point. You'll know it worked when circles appear at every x, y coordinate. -
Create a horizontal bar chart using
plt.barh(subjects, scores)instead ofplt.bar(). You'll know it worked when bars grow horizontally instead of vertically. -
Generate a list of 100 numbers using a list comprehension with
(i % 10)and plot a histogram withbins=10. You'll know it worked when you see a flat distribution — every bin has about the same height. -
Use
plt.subplots(2, 1)to stack two charts vertically: a line chart on top and a bar chart below. You'll know it worked when both charts appear in the same figure, stacked.
Data Visualizer!
You've turned raw numbers into charts that tell stories!
Line plots, scatter plots, bar charts, histograms, and subplots — these are the bread and butter of every data scientist.
The next chapter takes you into NumPy, where you'll learn to crunch large amounts of numerical data at lightning speed. Let's keep coding!