Data Visualization with Matplotlib
When we’re working with data, it’s often easier to understand it visually. Today we’ll see how to visualize data in Python and discuss a few best practices for communicating what we find.
Figures and axes
We’ll use Matplotlib, a Python library for making plots. In Matplotlib, a figure is the whole image, and an Axes is the area where we draw a plot. A figure can contain several plots, each with its own axes and labels.
We’ll use college data to see how the cost of attending a college relates to what its former students earn. Let’s start with three schools. For each one we have the average annual net price (the cost after grants and scholarships) and median annual earnings ten years after starting college.
A scatter plot shows each school as a point, with price on the horizontal axis and earnings on the vertical axis. To run this example, install Matplotlib with python -m pip install matplotlib.
import matplotlib.pyplot as plt
names = ['Pomona', 'CMC', 'Pitzer']
price = [18084, 19489, 40261]
earnings = [84281, 127532, 72270]
fig, ax = plt.subplots(layout='constrained') # One figure with one plot
ax.scatter(price, earnings)
for name, x, y in zip(names, price, earnings):
ax.text(x, y, name, ha='center', va='bottom')
ax.margins(0.15) # Leave room for the names
ax.set(xlabel='Average annual net price ($)',
ylabel='Median annual earnings 10 years after entry ($)',
title='Costs and earnings at three Claremont colleges')
fig.savefig('colleges.png', dpi=160)
plt.show() # Display the figure
The loop pairs each name with its price and earnings using zip, then writes the name above the dot with ax.text. Pomona is first in all three lists, so its price of $18,084 is paired with its earnings of $84,281. If we sorted the lists separately, a dot could show one college’s price and another’s earnings.
Choosing a plot
The type of plot depends on what we want to learn. To study the relationship between two quantities, we can plot each pair of values. To study the distribution of one quantity, we can group its values into intervals and count how many fall in each. This second plot is called a histogram, and its intervals are called bins.
(All the tables from this reading are available as a PDF here.)
| Plot | Matplotlib call | What it shows |
|---|---|---|
| Scatter plot | ax.scatter(x, y) |
Each dot gives two measurements for one observation. |
| Histogram | ax.hist(values, bins=edges) |
One bar per interval. Its height shows how many values fall in that interval. |
| Line plot | ax.plot(x, y) |
A line connects the points in the order given. Use it to follow a change over time or trace a path. |
| Bar chart | ax.bar(names, values) |
One bar per category. Its length shows the amount for that category. |
Let’s use a histogram to see which prices are most common among 95 California colleges. Save california-colleges.csv in the folder where you’ll run the code. Each row represents one college. We’ll read the price column and group the prices into $10,000 bins.
import csv
import matplotlib.pyplot as plt
with open('california-colleges.csv', encoding='utf-8', newline='') as file:
prices = [int(row['annual_net_price']) for row in csv.DictReader(file)]
fig, ax = plt.subplots(layout='constrained')
ax.hist(prices, bins=[0, 10000, 20000, 30000, 40000, 50000, 60000],
edgecolor='white')
ax.set(xlabel='Average annual net price ($)', ylabel='Number of colleges',
title='Annual net prices at California colleges')
fig.savefig('net-price-histogram.png', dpi=160)
plt.show()
The first bar has a height of 9, meaning that nine colleges cost less than $10,000 per year on average after aid. A price of exactly $10,000 belongs in the second bin. Matplotlib includes the upper endpoint only for the last bin.
A line plot connects observations in order. When we measure the same quantity each year, the slope between two points shows how quickly it rose or fell over that period.
How did the number of applications to CMC change from one year to the next? We’ll put the years in chronological order and use marker='o' to mark each fall’s count. The figures come from CMC’s annual report.
import matplotlib.pyplot as plt
years = [2019, 2020, 2021, 2022, 2023]
applications = [6066, 5306, 5632, 5709, 5799]
fig, ax = plt.subplots(layout='constrained')
ax.plot(years, applications, marker='o')
ax.set_xticks(years)
ax.set(xlabel='Fall entering class', ylabel='Number of applications',
title='Applications to Claremont McKenna College')
fig.savefig('cmc-applications.png', dpi=160)
plt.show()
The steepest stretch is between 2019 and 2020, when CMC received 760 fewer applications. The line then rises for three years.
Axis scales
In a bar chart, the length of each bar represents an amount. Starting the axis at zero makes a bar for twice the amount twice as long. In a line plot or scatter plot, the position of each point gives its value. A narrower axis range can make small changes easier to see.
When comparing plots side by side, use the same axis limits and panel sizes so the same distance represents the same difference in value.
Both charts show median earnings of $84,025 for Scripps and $84,281 for Pomona. On the left, the vertical axis starts at $84,000. The visible bars represent just the $25 and $281 above that amount. On the right, the axis starts at zero and the bars show the full amounts.

To make the comparison in Python, plt.subplots(1, 2) creates two plots in one row. We draw the same bars in both and use set_ylim to change the vertical range.
import matplotlib.pyplot as plt
fig, (left, right) = plt.subplots(1, 2, figsize=(8, 3.4), layout='constrained')
fig.suptitle('Median annual earnings 10 years after college entry')
for ax in (left, right):
bars = ax.bar(['Scripps', 'Pomona'], [84025, 84281])
ax.bar_label(bars, labels=['$84,025', '$84,281'], padding=3)
ax.ticklabel_format(axis='y', useOffset=False)
left.set(title='Axis starts at $84,000', ylabel='Earnings ($)')
right.set_title('Axis starts at $0')
left.set_ylim(84000, 84400)
right.set_ylim(0, 95000)
fig.savefig('baselines.png', dpi=160)
plt.show()For more before-and-after examples, see Misleading axes on graphs. In the first pair, compare the bars for Germany and France. How much longer does the German workweek look in each version?
Labels and styles
A plot should make sense to someone who hasn’t seen the dataset. Give it a title that describes the comparison and label each axis with the quantity and its units. Use the caption to explain where the data came from and who was included.
When a plot includes several groups, choose colors that are easy to distinguish and give each group its own marker or line pattern. That way the groups are still identifiable when the plot is printed in black and white. A legend tells the reader which group each symbol represents.
Here are the prices and earnings for all 95 colleges. Circles represent public colleges and triangles represent private nonprofits.

Harvey Mudd and Pitzer are close on the price axis (within $600) and far apart on the earnings axis (about $92,000). The two colleges enroll different students and offer different majors. We can compare their median earnings, but we can’t use that difference to predict how much more a particular student would earn by attending Harvey Mudd.
The College Scorecard reports earnings for former federal aid recipients who were working and no longer enrolled. We used the 2022 data for California public and private nonprofit colleges that primarily award bachelor’s degrees and have both measurements.
To plot the two groups, call scatter twice on the same Axes. Each call supplies a marker shape and a label for the legend. The alpha argument makes the dots partly transparent, so places where several overlap appear darker. To label just the five Claremont colleges, we look up their names in a dictionary. Save the college CSV beside your script to run this example.
import csv
import matplotlib.pyplot as plt
with open('california-colleges.csv', encoding='utf-8', newline='') as file:
colleges = list(csv.DictReader(file))
names = {'Claremont McKenna College': 'CMC', 'Harvey Mudd College': 'Harvey Mudd',
'Pitzer College': 'Pitzer', 'Pomona College': 'Pomona', 'Scripps College': 'Scripps'}
fig, ax = plt.subplots(figsize=(8, 5), layout='constrained')
for sector, shape in [('Public', 'o'), ('Private nonprofit', '^')]:
group = [row for row in colleges if row['sector'] == sector]
prices = [int(row['annual_net_price']) for row in group]
earnings = [int(row['median_earnings_10_years_after_entry']) for row in group]
ax.scatter(prices, earnings, marker=shape, alpha=0.65, label=sector)
for row in colleges:
if row['college'] in names:
x = int(row['annual_net_price'])
y = int(row['median_earnings_10_years_after_entry'])
ax.annotate(names[row['college']], (x, y), xytext=(5, 5),
textcoords='offset points', fontsize=9)
ax.set(xlabel='Average annual net price ($)',
ylabel='Median annual earnings 10 years after entry ($)',
title='Costs and earnings at California colleges', xlim=(0, 52000), ylim=(0, 180000))
ax.legend()
fig.savefig('california-colleges.png', dpi=160)
plt.show()| Feature | Matplotlib call | What it does |
|---|---|---|
| Title | ax.set_title('Annual net price') |
Names the plot. |
| Axis labels | ax.set_xlabel('Price ($)') |
Labels the horizontal axis. Use set_ylabel for the vertical axis. |
| Axis limits | ax.set_ylim(0, 95000) |
Sets the bottom and top of the plot. Use set_xlim for the left and right limits. |
| Legend | ax.legend() |
Displays the names supplied with label in the plotting calls. |
For line plots, pass these options to ax.plot. A dashed line and a solid line are a common choice for comparing two series.
| Line feature | Argument | Choices |
|---|---|---|
| Pattern | linestyle='--' |
'-' solid, '--' dashed, ':' dotted |
| Thickness | linewidth=2 |
Width in points. A larger number draws a thicker line. |
| Color | color='tab:blue' |
Accepts a color name or a hex color such as '#174a7e'. |
| Points on the line | marker='o' |
Marks each observation with a circle. Use markersize=6 to set its size in points. |
For scatter plots, pass these options to ax.scatter. Smaller markers are useful when many points overlap.
| Marker feature | Argument | Choices |
|---|---|---|
| Shape | marker='^' |
'o' circle, 's' square, '^' triangle, 'x' cross |
| Size | s=36 |
Marker size in points squared. Larger values give bigger markers. |
| Opacity | alpha=0.6 |
Ranges from 0 (invisible) to 1 (opaque). |
| Color | color='tab:orange' |
Sets the marker color. |