DS 208 · Week 8

Data Visualization

Turning a summarised table into a chart that shows the pattern clearly, with matplotlib for control and seaborn for speed.

Programming for Data Science · University of the Philippines Cebu

Outline

From numbers to charts

Key terms

Ten terms introduced this week

figure

The whole picture: the canvas that is sized and saved as an image file.

e.g. fig.savefig("chart.png")

axes

One plotting area inside a figure, with its own x and y axis. Data are drawn on it.

e.g. fig, ax = plt.subplots() gives one figure and one axes

plot

To draw data onto an axes; ax.plot draws points joined by a line.

e.g. ax.plot([2021, 2022], [12, 15])

marker

The symbol drawn at each data point: a dot, a square, a triangle.

e.g. marker="o" puts a dot on every point

label

Text that names an axis or the chart, ideally with the unit.

e.g. ax.set_ylabel("Sales (₱)")

legend

The small key that says which colour or marker means which group.

e.g. ax.legend() after label="Cebu"

subplot

One of several small charts arranged in a grid inside one figure.

e.g. plt.subplots(1, 2) makes two side by side

histogram

Bars that count how many values fall in each range (bin) of one column.

e.g. ax.hist(scores, bins=5)

matplotlib

The basic Python charting library, in which every part is drawn and labelled explicitly.

e.g. import matplotlib.pyplot as plt

seaborn

A library built on matplotlib that draws statistical charts from a DataFrame in one call.

e.g. sns.histplot(data=df, x="pop") (Colab, not the browser lab)

Previous session

A summary table does not show its shape

The groupby in week 7 gave numbers per region. Which region is largest, and by how much, is much faster to see in a bar chart than in a column of digits.

The table

Exact, but every row must be read to compare.

The chart

Approximate, but the pattern is visible immediately.

About the tool

matplotlib began as a neuroscientist’s workaround

2003

matplotlib

John D. Hunter, analysing EEG brain recordings, cannot find a Python plotting library, so he writes one.

2012

New leaders

Hunter dies in August; the community carries the project on.

2013

seaborn

Michael Waskom’s first releases: statistical charts built on matplotlib.

2024

NASA grant

NASA funds matplotlib’s continued development.

Sourcematplotlib.org: History; Wikipedia: Matplotlib; seaborn release notes; pyplot docs (“MATLAB-like”)

About the tool

How widely matplotlib and seaborn are used

SourceDownloads: pypistats.org, without mirrors, retrieved 11 Oct 2026; black hole: Wikipedia: Matplotlib

Runnable code

Charts on these slides draw in the browser

As in weeks 5 to 7, a block with a ▶ Run / Edit button runs in the browser and can be changed. A chart appears as a picture under the code. The first run downloads Python, pandas and matplotlib, which takes 10 to 20 seconds.

What does not run here

seaborn is not available in the browser, and the flood data cannot be downloaded there. Those blocks have no button; the companion notebook runs them.

import io, sys print("pandas version:", pd.__version__) print("64-bit Python:", sys.maxsize > 2**32) t = pd.read_csv(io.StringIO("city,pop\nCebu,964000")) print(t.dtypes) pandas version: 3.0.5 64-bit Python: True city str pop int64 dtype: object
  • pd.__version__the installed pandas: 3.0.5 on the laptop, 2.2.0 in the browser
  • t.dtypeseach column’s type: str on the laptop, object in the browser
Part A

matplotlib

The foundation under every Python chart.

Weeks 6 and 7 reduced tables to summary numbers. This part draws them: matplotlib is the Python library (a package of ready-made code loaded with import) that draws charts, one instruction at a time.

Exercise · 3 min

A figure contains axes, and data are drawn on the axes

plt.subplots() returns a figure (the canvas) and an axes (the plot itself). Methods on ax draw and label.

Key terms

figure
the whole picture: the canvas that is sized and saved as a file
axes
one plotting area inside the figure, with its own x and y axis; a figure can hold several
axis
one of the two number lines (x across, y up) at the edge of an axes
plot
to draw data onto an axes; ax.plot draws points joined by a line

A method (week 4) is a function that belongs to an object, called with a dot: ax.plot(…).

Tasks

  1. Predict what the x-axis tick labels will show.
  2. Select ▶ Run / Edit and run the code.
  3. Change ax.plot to ax.bar and run again.

Result on the lecture laptop (select to reveal)

One line rising from 12 to 24, with a dip in 2023. The ticks read 2021.0, 2021.5, 2022.0, …: matplotlib treats the years as ordinary numbers. With ax.bar, the same five values become five bars. The next slide shows the line chart.

import matplotlib.pyplot as plt years = [2021, 2022, 2023, 2024, 2025] sales = [12, 15, 14, 20, 24] fig, ax = plt.subplots() ax.plot(years, sales) ax.set_title("Sales over time") plt.show()
  • fig, ax = plt.subplots()a figure (the whole picture) and one axes (the plotting area) inside it
  • ax.plot(years, sales)draw a line through the five points, x from years, y from sales
  • plt.show()display the finished chart
Output

Four lines of code produce one line chart

Line chart titled Sales over time: one blue line from 12 in 2021 up to 15 in 2022, down to 14 in 2023, then up to 20 in 2024 and 24 in 2025. The x axis ticks read 2021.0, 2021.5, 2022.0 and so on; neither axis has a label.

sales dip in 2023, then climb. The x axis shows 2021.5 and 2022.5 because matplotlib treats years as ordinary numbers, and neither axis says what it measures yet: labels come a few slides on.

Run with the week-8 lab’s lists: years = [2021, 2022, 2023, 2024, 2025], sales = [12, 15, 14, 20, 24]. Every chart in this deck is the real output of the code on the slide before it.

Case study

The flood data, loaded from the course API

The rest of Part A charts the 34,079 flood control projects, with week 6’s duration column: days from start to completion.

Why not pd.read_csv(url)?

pandas downloads with urllib, which this site’s bot protection answers with 403 Forbidden. requests gets through.

The browser cannot download the data, so the flood blocks have no Run button; the companion notebook runs them, and each chart that follows was drawn by its slide’s code.

import io, requests url = "https://portal.latarak.com/api/flood/export.csv" resp = requests.get(url, timeout=60) df = pd.read_csv(io.StringIO(resp.text)) # week 6's derived column: days from start to completion for col in ["start_date", "completion_date"]: df[col] = pd.to_datetime(df[col], errors="coerce") df["duration"] = (df.completion_date - df.start_date).dt.days print(df.shape) (34079, 16)
  • requests.get(url)download the whole table in one request
  • df["duration"] = …days from start to completion; NaN where a date is missing
  • (34079, 16)34,079 projects; 15 columns from the file plus duration
Starting with subplots()

One call returns both objects, named

plt.plot() draws onto whatever figure is "current", which becomes ambiguous once there are two. Requesting the objects explicitly avoids that ambiguity.

fig for the file, ax for the drawing

Saving and sizing happen on fig. Drawing and labelling happen on ax.

fig, ax = plt.subplots(figsize=(8, 5)) ax.scatter(df.budget, df.duration, alpha=0.05) ax.set_xlabel("Budget (PHP)") ax.set_ylabel("Duration (days)") plt.show()
  • plt.subplots(figsize=(8, 5))one figure, 8 by 5 inches, with one axes
  • ax.scatter(df.budget, df.duration, alpha=0.05)one dot per project; alpha makes each dot 95% transparent
  • set_xlabel / set_ylabelname each axis, with its unit
Output

Budget against duration: dots concentrated at the left edge

Scatter plot of duration in days (0 to about 2,700) against budget in pesos (0 to about 1.05 times 10 to the 9). Faint blue dots merge into a solid block below 0.2 billion pesos and 700 days; a few lone dots reach out to the right.

even at alpha=0.05 the left edge is solid blue. Most budgets are small and a few are huge, so nearly every dot is squeezed into the first fifth of the axis. The 1e9 at the bottom right means the ticks are in billions of pesos (0.2 = ₱200 million).

Data: DPWH flood-control projects (BetterGov.ph mirror, CC0), 34,079 rows; 27,664 have a duration.

A grid of axes

subplots returns an array for more than one axes

Two numbers give a grid. axes is then a NumPy array and is indexed like one. Each small chart in the grid is called a subplot.

Purpose of sharey

Panels with different y-limits appear comparable but are not. A shared axis makes a multi-panel figure honest.

fig, axes = plt.subplots(2, 2, figsize=(12, 8), sharey=True) axes[0, 0].hist(df.budget, bins=30) axes[0, 1].hist(df.duration, bins=30) fig.tight_layout() # stops overlap plt.show()
  • plt.subplots(2, 2, …, sharey=True)a 2 × 2 grid of axes that share one y scale
  • axes[0, 0]row 0, column 0: the top-left axes; axes.flat loops over all four
  • fig.tight_layout()space the panels so labels do not overlap
Output

Two histograms drawn and two axes empty

A 2 by 2 grid of plots sharing one y axis from 0 to about 22,000. Top left: a budget histogram with one tall bar near zero (about 21,500 projects) and a few short ones. Top right: a duration histogram peaking around 200 days. The bottom two panels are empty.

budget piles into the first one or two bars: most projects are small, a few are enormous. Because of sharey=True both histograms use the same 0–22,000 scale, so their bar heights can be compared directly.

Only the two hist lines and tight_layout(): the loop then fills the empty panels with whichever columns cols lists. Data: DPWH flood-control projects (BetterGov.ph mirror, CC0), 34,079 rows; 27,664 have a duration.

Overplotting

Overplotting with 27,664 dots

Overplotting is when dots pile on top of each other until their number can no longer be seen. Every real scatter in this course has too many points. There are three fixes, and the first is usually sufficient.

alpha first, then hexbin

Transparency shows density at no cost. When that saturates, the plane is binned instead of drawing points.

x, y = df.budget, df.duration # 1. transparency and small dots, on a log axis fig, ax = plt.subplots() ax.scatter(x, y, alpha=0.05, s=4) ax.set_xscale("log") plt.show() # 2. a reproducible sample d = df.sample(2000, random_state=42) # 3. bin the plane (hexbin's own log axis) pos = x > 0 fig, ax = plt.subplots() ax.hexbin(x[pos], y[pos], gridsize=40, cmap="Blues", xscale="log") plt.show()
  • alpha=0.05, s=4fix 1: faint, small dots, so dense areas look darker
  • df.sample(2000, random_state=42)fix 2: plot a reproducible sample of 2,000 projects
  • ax.hexbin(…, xscale="log")fix 3: count the dots in hexagons; budgets of 0 are left out, since log(0) does not exist
Output

Fixes 1 and 3 on a log budget axis

Scatter of duration against budget on a log x axis from 10 to the 6 to 10 to the 9 pesos: small faint dots form vertical stripes at round budgets and drift upward as budgets grow.
1 · alpha=0.05, s=4, then set_xscale("log")
Hexbin chart of the same data on a log x axis: pale hexagons everywhere, the darkest ones around 50 million pesos and 150 to 300 days.
3 · hexbin(…, xscale="log"), budgets above 0

once the budget axis is logged, both show bigger budgets tending to take longer, and budgets bunching at round numbers (the vertical stripes). The darkest hexagon is the most common kind of project.

Here x is df.budget and y is df.duration. Run as first written, hexbin followed by set_xscale("log") drew an empty chart, so the code passes xscale="log" to hexbin; it refuses the 939 projects with a ₱0 budget, so those are dropped first.

Conceptual model

Parts of a chart

figure (the canvas) Sales over time ← title Year ← x-axis label Sales (₱) ← y-axis label
Exercise · 3 min

An unlabelled chart cannot be interpreted

Three lines make an unlabelled plot interpretable. Labels are needed every time, because the meaning of the axes is easily forgotten later.

A chart without labels is a map without a legend or place names; the shapes are present but their meaning is not.

Tasks

  1. Predict what ax.set_xticks(years) changes.
  2. Select ▶ Run / Edit and run the code.
  3. Delete the set_title line and run again. What can a reader no longer tell?

Result on the lecture laptop (select to reveal)

The x ticks become the five whole years instead of 2021.0, 2021.5, …; both axes now say what they measure. Without the title, nothing says whose sales these are or which years they cover.

# years, sales: the first chart's data fig, ax = plt.subplots() ax.plot(years, sales) ax.set_xticks(years) ax.set_xlabel("Year") ax.set_ylabel("Sales (PHP thousands)") ax.set_title("Cebu branch, 2021-2025") plt.show()
  • ax.set_xticks(years)put a tick at each year, and only there
  • set_xlabel / set_ylabel / set_titlewhat is across, what is up (with its unit), and what the chart is about
Part B

Chart types

Matching the chart to the question.

Part A made and labelled a figure. This part covers choosing which picture to draw, because each chart type answers a different kind of question.

Choosing by question

Four charts cover most needs

ChartShowsUse when
Linea trend over timethe x-axis is ordered (dates, steps)
Barcompare categoriesa value per named group
Scattera relationshiptwo numbers, one point per row
Histograma distributionthe spread of one number
The small tables

Week 7’s eight cities, with their areas

The chart-type examples in Part B use the eight cities from week 7, merged with their land areas, and the total population of each region.

  • cities.merge(areas, on="city")week 7’s merge: population and area in one table, both
  • both.groupby("region")["pop"].sum()the total population of each region’s cities: by_region

SourceLand areas from each city’s Wikipedia article, rounded to whole km²; populations are approximate 2020 census figures.

import io csv_text = """city,region,pop Quezon City,Luzon,2960000 Manila,Luzon,1847000 Baguio,Luzon,366000 Cebu,Visayas,964000 Iloilo,Visayas,457000 Tacloban,Visayas,251000 Davao,Mindanao,1777000 Cagayan de Oro,Mindanao,728000""" cities = pd.read_csv(io.StringIO(csv_text)) areas = pd.DataFrame({ "city": ["Quezon City", "Manila", "Baguio", "Cebu", "Iloilo", "Tacloban", "Davao", "Cagayan de Oro"], "area_km2": [172, 42, 58, 315, 78, 202, 2444, 413]}) both = cities.merge(areas, on="city") by_region = both.groupby("region")["pop"].sum()
Trend & comparison

Line for time, bar for categories

A line connects ordered points and implies continuity. Bars sit apart and imply separate items to compare.

A line chart resembles a temperature graph through the day, where hours follow each other; a bar chart resembles a height chart, where each bar is a separate person.

fig, (a1, a2) = plt.subplots(1, 2, figsize=(10, 4)) a1.plot(years, sales, marker="o") # trend over time a2.bar(by_region.index, by_region.values) # compare categories plt.show()
  • plt.subplots(1, 2, …)one row of two axes, side by side
  • a1.plot(years, sales, marker="o")a line for a trend over time, with a dot on each year
  • a2.bar(by_region.index, by_region.values)bars to compare categories: one per region
Line charts for time

Spending per year in one call

A line chart says "these points are connected in order". It is appropriate only for time or another genuine sequence.

A marker is the symbol drawn at each data point: "o" a dot, "s" a square, "^" a triangle.

No lines across categories

Connecting 18 regions implies that Region I leads into Region II. Unordered data require bars.

y = df.groupby("year").budget.sum() / 1e9 fig, ax = plt.subplots(figsize=(9, 4)) ax.plot(y.index, y.values, marker="o") ax.set_ylabel("Total budget (PHP billions)") plt.show() print(y.round(1).tail(3)) year 2024 369.3 2025 196.2 2026 0.0 Name: budget, dtype: float64
  • df.groupby("year").budget.sum() / 1e9total budget per year, in billions of pesos
  • ax.plot(…, marker="o")a line through the yearly totals, with a dot on each year
  • 2026 0.0the last two years are incomplete: the next slide
Output

Spending per year: chart

Line chart of total budget per year in billions of pesos, a dot on each year: about 53 in 2016, 127 in 2018, flat near 100 until 2021, then a steep climb to a peak of 369 in 2024, down to 196 in 2025 and to 0 in 2026.

the line climbs to a 2024 peak, then plunges to ₱196B in 2025 and to zero in 2026. The chart draws that plunge as confidently as every other year; the next two slides examine whether it is real.

Data: DPWH flood-control projects (BetterGov.ph mirror, CC0), 34,079 rows; 27,664 have a duration.

Data completeness

2024: ₱369B. 2025: ₱196B.

Either a 47% fall in flood control spending, or an export taken partway through the year.

Incomplete periods

An incomplete final year resembles a sharp decline

2026 has one project in it. 2025 has 3,475 against 2024’s 5,553. The dataset was exported mid-period, so the last values are partial, and the chart does not indicate this.

Two corrections

Drop the incomplete periods, or draw them differently (dashed, greyed) and label them. A partial period should not be plotted as if it were complete.

print(df.groupby("year").size().tail(3)) # 1. drop what is not comparable fig, ax = plt.subplots(figsize=(9, 4)) ax.plot(y[y.index <= 2024], marker="o") plt.show() # 2. or mark it: whole years solid, partial dashed fig, ax = plt.subplots(figsize=(9, 4)) ax.plot(y[y.index <= 2024], marker="o") ax.plot(y[y.index >= 2024], linestyle="--", color="grey") ax.annotate("partial year", xy=(2025, y[2025]), xytext=(2025.3, 250), arrowprops=dict(arrowstyle="->")) plt.show() year 2024 5553 2025 3475 2026 1 dtype: int64
  • y[y.index <= 2024]keep only the complete years
  • linestyle="--", color="grey"draw the incomplete years dashed and grey, so they read as different
  • ax.annotate(…)write a label on the chart, with an arrow to the point it explains
Output

The two corrections: charts

Line chart of total budget per year from 2016 to 2024 only, ending at its peak of 369 billion pesos.
drop: y[y.index <= 2024]
The same line from 2016 to 2024 in solid blue, then a grey dashed line down to 196 in 2025 and 0 in 2026, with an arrow labelled partial year pointing at 2025.
mark: solid to 2024, grey dashes after

on the left the partial years are gone, so the chart ends at the 2024 peak. On the right they stay but look different: the grey dashes signal “not comparable” before any label is read.

The note was placed with xy=(2025, y[2025]), xytext=(2025.3, 250). Data: DPWH flood-control projects (BetterGov.ph mirror, CC0), 34,079 rows; 27,664 have a duration.

Bar charts for categories

Sorted, horizontal, and starting at zero

Three decisions turn an unreadable bar chart into a readable one, and none of them is about colour: sort the bars by size, lay them sideways, and start the value axis at zero.

Horizontal for long labels

"National Capital Region" rotated 45 degrees is unreadable and takes a third of the figure. barh avoids this at no cost.

g = (df.groupby("region").budget.sum() .sort_values() / 1e9) fig, ax = plt.subplots(figsize=(7, 6)) ax.barh(g.index, g.values) ax.set_xlabel("Total budget (PHP billions)") plt.show() print(g.round(1).tail(3)) region Region V 155.6 National Capital Region 159.2 Region III 267.7 Name: budget, dtype: float64
  • .sort_values() / 1e9smallest first, so the longest bar ends up on top
  • ax.barh(g.index, g.values)horizontal bars: long region names stay readable
Output

The ranking: chart

Horizontal bar chart of total budget by region in billions of pesos, longest bar on top: Region III about 268, National Capital Region 159, Region V 156, down to Region XII and Region IX at about 36.

every region name is readable, the longest bar sits on top, and Region III’s bar is about 1.7 times NCR’s, which the eye sees at once without reading a number.

Data: DPWH flood-control projects (BetterGov.ph mirror, CC0), 34,079 rows; 27,664 have a duration.

Two charts, one figure

When a second y-axis is misleading

twinx() ("twin x") puts two scales on one plot: a second y axis on the right that shares the same x axis. It is the easiest way to imply a relationship that is not there, because the author chooses both scales.

Alternative

Two stacked panels with sharex=True. The comparison survives; the implied correlation (the suggestion that the two lines move together) does not.

totals = df.groupby("year").budget.sum() / 1e9 counts = df.groupby("year").size() # tempting, and easy to abuse fig, ax = plt.subplots() ax.plot(totals.index, totals.values) ax2 = ax.twinx() ax2.plot(counts.index, counts.values, color="red") plt.show() # better: two panels, one shared year axis fig, (a1, a2) = plt.subplots(2, 1, sharex=True) a1.plot(totals.index, totals.values) a2.bar(counts.index, counts.values) plt.show()
  • ax2 = ax.twinx()a second y axis on the right, sharing the x axis
  • plt.subplots(2, 1, sharex=True)the safer layout: two panels, one above the other, one year axis
Output

Twin axes compared with two stacked panels

Line chart with two y axes: blue total budget on the left (0 to 370 billion pesos) and red project counts on the right (0 to about 5,500). The two lines follow each other closely and meet at the 2024 peak and at zero in 2026.
twinx(): two scales on one plot
Two stacked panels sharing the year axis: top, a line of total budget per year; bottom, bars of projects per year, from about 1,800 in 2016 to 5,553 in 2024 and 3,475 in 2025.
better: two panels, sharex=True

on the left the lines seem to rise and fall as one, but only because matplotlib stretched each scale to fill the box; a different right-hand scale would pull them apart. On the right each measure keeps its own axis.

counts = projects per year, df.groupby("year").size(); totals = the yearly budget y; the twin axes sit on the spend-per-year chart. Data: DPWH flood-control projects (BetterGov.ph mirror, CC0), 34,079 rows; 27,664 have a duration.

Exercise · 3 min

Scatter for pairs, histogram for one column

A scatter plots one point per row to reveal whether two numbers move together. A histogram bins one column to show where values cluster.

A histogram cuts the range of values into equal slices called bins (e.g. 0–10, 10–20, …) and draws one bar per bin, as tall as the number of values that fall in it.

A histogram resembles grouping students by height band, counting how many are 150–155 cm, how many 155–160 cm, and so on.

Tasks

  1. Predict whether cities with a larger area have more people.
  2. Select ▶ Run / Edit and run the code.
  3. Change bins=5 to bins=2. What does the histogram hide now?

Result on the lecture laptop (select to reveal)

No clear pattern (correlation 0.24): Davao has the largest area, 2,444 km², but fewer people than Quezon City’s 172 km². With 5 bins the counts are 4, 1, 2, 0, 1; with 2 bins only 5 and 3 remain, and the single city above 2.4 million (Quezon City) disappears into the upper bar.

# both: cities with their areas (the tables slide) fig, (a1, a2) = plt.subplots(1, 2, figsize=(10, 4)) a1.scatter(both["area_km2"], both["pop"]) # do they move together? a2.hist(both["pop"], bins=5) # where do values cluster? plt.show()
  • a1.scatter(both["area_km2"], both["pop"])one dot per city: area across, population up
  • a2.hist(both["pop"], bins=5)count the cities in 5 equal-width population ranges
Review question

Question (select to reveal the answer)

Which chart shows the spread of exam scores across one class?

A · line chart
B · scatter plot
C · histogram
D · pie chart

C — histogram.

A histogram bins one column to show its distribution — where scores cluster and how wide they spread. A line implies order; a scatter needs two numbers.

Break

  Five minutes

Next: plotting with seaborn.

Part C

seaborn

Statistical charts, straight from a DataFrame.

Any chart can be built in matplotlib line by line. seaborn is a second library, built on top of matplotlib, that draws common statistical charts from a DataFrame in one call. (The in-browser lab has matplotlib only; seaborn runs in Colab.)

Column names, not arrays

Passing a DataFrame to seaborn

The whole frame is passed, with a column named for each axis. seaborn reads the data directly, applies sensible defaults and labels the axes.

matplotlib takes two lists of numbers. seaborn takes the whole table and the column names for each axis ("region" across, "pop" up).

import seaborn as sns sns.barplot(data=both, x="region", y="pop") plt.show() sns.scatterplot(data=both, x="area_km2", y="pop") plt.show()
  • sns.barplot(data=both, x="region", y="pop")name the table once, then the columns; by default the bar shows each region’s mean, with an error bar
  • sns.scatterplot(…)the same style for a scatter: columns by name, axes labelled automatically
Common error

Why ax= fails with some seaborn functions

Half of seaborn’s functions return a figure, not an axes.

Two families

Axes-level and figure-level functions

This distinction explains nearly every seaborn error message that beginners encounter.

Key terms

axes-level
draws one chart onto an axes supplied with ax=
figure-level
builds a whole new figure itself, possibly with many subplots
facet
repeat the same chart once per group, in a grid of small panels

Identifying them by name

The *plot functions that end in plot and take ax= are axes-level. relplot, displot, catplot are figure-level.

import seaborn as sns # AXES-level: give it an ax fig, ax = plt.subplots() sns.scatterplot(data=both, x="area_km2", y="pop", ax=ax) plt.show()
import seaborn as sns # FIGURE-level: it owns the figure, one panel per region g = sns.relplot(data=both, x="area_km2", y="pop", col="region") plt.show()
  • ax=ax"draw on this axes": the one made with plt.subplots()
  • col="region", col_wrap=4one panel per region, four panels per row
  • g.fig / g.axesg is the grid seaborn built; these give its figure and its axes
  • relplot(…, ax=ax)if ax= is passed anyway, seaborn prints a warning that relplot does not accept it and ignores it: the chart appears in a new figure, not on the given axes
Choosing a family

Figure-level for facets, axes-level for composed layouts

For one chart placed inside a controlled layout, axes-level is used. For the same chart repeated per group, figure-level is used and builds the grid.

Axes-level plots cannot be faceted

There is no col= on scatterplot. This is the usual reason for writing manual subplot loops.

# d: the 2,000-project sample from the overplotting slide g = sns.relplot(data=d, x="budget", y="duration", col="region", col_wrap=6, height=2.2, alpha=0.3) g.set(xscale="log") g.savefig("by_region.png", dpi=150) # g.savefig, not plt.savefig plt.show()
  • col="region", col_wrap=6one panel per region, six panels to a row
  • g.set(xscale="log")the same log budget axis on every panel
  • g.savefig(…)a figure-level plot is saved through its own object, not plt.savefig
Output

18 panels from one call

A grid of 18 small scatter plots, 6 per row, one per region, each showing duration against budget on the same log budget axis and the same duration axis up to about 1,300 days. In the bottom row two long panel titles run into each other.

every panel shares the same axes, so regions compare at a glance: Region III and NCR are dense, Central Office has only a handful of dots. Two long region names collide in the bottom row; that is seaborn’s default output.

d is the 2,000-row sample from the overplotting slide, df.sample(2000, random_state=42). Data: DPWH flood-control projects (BetterGov.ph mirror, CC0), 34,079 rows; 27,664 have a duration.

Common seaborn functions

Frequently used seaborn charts

FunctionDrawsAdditional feature
sns.histplota histogramoptional density curve (a smooth line tracing the bars’ shape)
sns.boxplotspread per groupmedian + outliers at a glance
sns.scatterplota relationshiphue= colours by a category
sns.barplota value per groupa confidence bar (a thin line showing how uncertain each average is) automatically
Legends

Legends only for multiple series

A legend is the small key that says which colour or marker means what. A series is one set of data drawn as one line or one set of dots. A legend on a single-series chart is noise. On a multi-series chart it is essential, and its placement matters.

Direct labels where possible

Two or three series read better annotated at their right-hand end than via a legend the eye has to travel to.

t = df[df.year <= 2025].pivot_table(index="year", columns="region", values="budget", aggfunc="sum") / 1e9 def draw(ax): ax.plot(t.index, t["Region III"], label="Region III") ax.plot(t.index, t["National Capital Region"], label="NCR") fig, ax = plt.subplots() draw(ax) ax.legend(loc="upper left", frameon=False) plt.show() # outside, saved WITHOUT bbox_inches="tight" fig, ax = plt.subplots() draw(ax) ax.legend(bbox_to_anchor=(1.02, 1), loc="upper left") fig.savefig("legend_outside.png", dpi=150)
  • label="Region III"the name the legend shows for this line
  • ax.legend(loc="upper left", frameon=False)draw the legend in a corner, without a box
  • bbox_to_anchor=(1.02, 1)outside the right edge: save with bbox_inches="tight" or it is cropped (next slide)
Output

Legend inside, and outside without a tight save

Two lines of yearly budget in billions of pesos, 2016 to 2025: Region III in blue rising to about 74 in 2024, NCR in orange to about 28. A legend with no frame sits in the top-left corner.
loc="upper left", frameon=False
The same chart with the legend placed outside the right edge and saved with default settings: the legend is cut off at the image border, so only the coloured line samples and the first letter of each name show.
outside, saved without bbox_inches="tight"

inside, the key fits the empty top-left corner. Outside, a default save cuts the names off at the image edge; saving with bbox_inches="tight" brings the whole key back.

x = the years; a, b = Region III’s and NCR’s yearly budget in PHP billions, from df.groupby(["year", "region"]).budget.sum(). Data: DPWH flood-control projects (BetterGov.ph mirror, CC0), 34,079 rows; 27,664 have a duration.

Setting the style

Style set once at the top of the notebook

Consistent figures across a report come from one call, not from repeating the same arguments in every chart.

Theme, then palette

whitegrid for anything with a y-scale to read against; ticks for scatter plots where a grid adds nothing.

import seaborn as sns sns.set_theme(style="whitegrid", palette="colorblind", context="talk") # context scales ALL text at once: # paper < notebook < talk < poster
  • style="whitegrid"white background with light grid lines
  • palette="colorblind"the set of colours used for groups, chosen to stay distinguishable for colour-blind readers
  • context="talk"scale all text and lines for a projector
Rendering errors

Four errors and what each one means

SymptomCauseFix
Nothing appears in the notebookNo plt.show(), or a non-interactive backendAdd %matplotlib inline
Labels cropped in the saved fileDefault save clips outside the axes boxbbox_inches="tight"
relplot ignores ax= (with a warning)It is figure-level and owns its figureUse scatterplot(ax=ax)
Panels overlap each otherDefault spacing does not account for labelsfig.tight_layout()
Honest design

Avoiding misleading charts

Bars start at zero

A truncated bar axis multiplies differences

A bar’s meaning is its length. Cutting the axis changes every length while the numbers remain technically correct.

Lines are different

A line chart encodes position, not length, so a non-zero baseline is acceptable and often necessary to show the change.

rates = ((df.status == "Completed") .groupby(df.region).mean().sort_values()) print(rates.round(3).iloc[[0, -1]]) for top in [1, 0.95]: fig, ax = plt.subplots(figsize=(10, 4)) ax.bar(rates.index, rates.values) ax.set_ylim(0 if top == 1 else 0.6, top) # full, then truncated plt.show() region Region IX 0.656 Region XII 0.920 Name: status, dtype: float64
  • (df.status == "Completed").groupby(df.region).mean()the completion rate of each region: True counts as 1
  • ax.set_ylim(…)first 0 to 1 (honest), then 0.6 to 0.95 (truncated)
  • 0.656 / 0.920Region IX and Region XII: a 1.4× ratio that the truncated axis draws as about 5.7×
Output

The same numbers on two y axes

Bar chart of completion rate by region on a 0 to 1 axis, sorted: the bars rise gently from about 0.66 (Region IX) to 0.92 (Region XII). The region names along the bottom overlap into an unreadable strip.
set_ylim(0, 1)
The same bars on an axis from 0.6 to 0.95: Region IX’s bar is now a stub and Region XII’s towers over it. The region names still overlap.
set_ylim(0.6, 0.95)

on the left the bars differ modestly, which is accurate. On the right the same numbers make Region XII look almost six times Region IX. The names crashing along the bottom are the long-label problem that barh solves.

rates = each region’s share of projects with status Completed, sorted. Data: DPWH flood-control projects (BetterGov.ph mirror, CC0), 34,079 rows; 27,664 have a duration.

Declaring a log scale

Readers assume a linear scale unless told otherwise

On a log axis (short for logarithmic), equal distances are equal ratios, not equal amounts. This is a different kind of chart and must be labelled as such.

In the axis label

Not only in the caption: the label stays with the image when it is copied into a slide.

fig, ax = plt.subplots() ax.scatter(df.budget, df.duration, alpha=0.05, s=4) ax.set_xscale("log") ax.set_xlabel("Budget (PHP, log scale)") ax.set_ylabel("Duration (days)") plt.show()
  • ax.set_xscale("log")equal steps on the axis now mean equal ratios: 10M to 100M is as wide as 100M to 1B
  • "Budget (PHP, log scale)"say so in the label, or readers assume a linear scale
Output

The same scatter, labelled as log

The budget against duration scatter again, now with a log budget axis from 10 to the 6 to 10 to the 9 pesos labelled Budget (PHP, log scale): the dots spread across the whole width in vertical stripes and drift upward as budgets grow.

the same dots as the first scatter now fill the width. The ticks go 106, 107, 108, each ten times the last, and the axis label says so.

The first scatter (figsize=(8, 5), alpha=0.05) with these two lines added. Data: DPWH flood-control projects (BetterGov.ph mirror, CC0), 34,079 rows; 27,664 have a duration.

Worked example

Colour choice for meaning and accessibility

About 8% of men have some form of colour-vision deficiency. Red-green deficiency is the most common, and red-green is also a common default.

A colormap (cmap) is a colour scale that turns numbers into colours, like a heat map from pale to dark.

Three kinds of colormap

Sequential for magnitude, diverging for a meaningful midpoint, qualitative for unordered categories. Using the wrong family misstates the data.

import numpy as np import matplotlib.pyplot as plt grid = np.arange(12).reshape(3, 4) # 0 to 11 fig, (a1, a2) = plt.subplots(1, 2, figsize=(8, 3)) a1.imshow(grid, cmap="viridis") # sequential: low to high a2.imshow(grid - 5.5, cmap="RdBu_r") # diverging: centred on 0 plt.show()
  • cmap="viridis"sequential: low to high, readable in colour-blind vision and in greyscale
  • cmap="RdBu_r"diverging: two colours meeting at a middle value (here 0)
Annotation

Writing the message on the chart

A reader should not have to find the conclusion in the dots, so it is marked on the chart.

One annotation, not five

Two arrows mean the chart has two messages, which usually means it should be two charts.

d = df.dropna(subset=["duration"]) # projects with a duration q1, q3 = d.budget.quantile([.25, .75]) top = d[d.budget >= q3].duration.median() low = d[d.budget <= q1].duration.median() co = df[df.region == "Central Office"] x0, y0 = co.budget.median(), co.duration.median() fig, ax = plt.subplots() ax.scatter(df.budget, df.duration, alpha=0.05, s=4) ax.set_xscale("log") ax.annotate("Central Office: 180 projects,\nmedian PHP 144.5M", xy=(x0, y0), xytext=(x0 * 2, y0 + 500), arrowprops=dict(arrowstyle="->")) ax.set_title(f"Larger projects take longer: {top:.0f} vs {low:.0f} median days") plt.show()
  • q1, q3 = d.budget.quantile([.25, .75])the cheapest and the most expensive quarter of the projects that have a duration
  • ax.annotate(text, xy=…, xytext=…)the note, the point it explains, and where the text sits
  • ax.set_title(f"…")the title states the finding, computed from the data: 269 against 119 median days
Output

The finding written on the chart

Log-scale scatter of duration against budget titled Larger projects take longer: 269 vs 119 median days. An arrow points at about 144.5 million pesos and 448 days, with the note Central Office: 180 projects, median PHP 144.5M.

the title states the finding and one arrow points at the one group being discussed, so the message is clear without searching through the dots. The note runs past the right edge because xytext doubles x0; a tight save keeps it in the file.

x0, y0 = Central Office’s median budget (₱144.5M) and median duration (448 days), on the log-scale scatter from the previous slides. Data: DPWH flood-control projects (BetterGov.ph mirror, CC0), 34,079 rows; 27,664 have a duration.

Saving

Adjusting the layout and saving at high resolution

tight_layout() stops labels clipping; savefig with a higher dpi exports a crisp image for a report or slide.

dpi means "dots per inch": more dots give a sharper, larger image file.

fig, ax = plt.subplots() ax.bar(by_region.index, by_region.values) fig.tight_layout() fig.savefig("pops.png", dpi=150) plt.show() # display in the notebook
  • fig.tight_layout()make room for the labels before saving
  • fig.savefig("pops.png", dpi=150)write the chart to a file at 150 dots per inch
  • plt.show()display it in the notebook as well
Saving options

Two arguments that prevent cropped labels

The default save clips anything outside the axes box — which is exactly where rotated tick labels and legends live.

dpi by destination

150 for a slide, 300 for print. The default 100 looks soft on any modern screen.

fig, ax = plt.subplots() ax.scatter(both["area_km2"], both["pop"]) fig.savefig("area_pop.png", dpi=150, bbox_inches="tight") # vector, for a report that gets zoomed fig.savefig("area_pop.pdf", bbox_inches="tight") # in a script, close what you save plt.close(fig)
  • bbox_inches="tight"trim the image to everything drawn, so nothing outside the axes is cropped
  • "area_pop.pdf"a vector file: it stays sharp when zoomed
  • plt.close(fig)free the figure’s memory; a script that saves many charts should close each
Checklist

Checks before a chart is shared

CheckWhy it matters
Both axes labelled, with units"Budget" is not a unit. "Budget (PHP)" is.
Title states the finding"Larger projects take longer" is more informative than "Budget vs Duration".
Bars start at zeroLength is the encoding; truncating it misstates ratios.
Log scales declared in the labelOtherwise the reader assumes linear distances.
n stated somewhere"27,664 projects with a completion date" — the denominator is part of the claim.
Saved with bbox_inches="tight"Otherwise the labels are cropped off.
Exercise · 8 min

A complete, defensible chart

1 · Create the figure

Scatter budget against duration with subplots(). Fix the overplotting with alpha, and log the x-axis.

2 · Label it fully

Both axes with units, a title that states a finding rather than naming the variables.

3 · Facet it

Rebuild as relplot with col="region", col_wrap=6. Confirm the axis limits are shared.

4 · Save both

PNG at dpi=150 with bbox_inches="tight". Open the file and check nothing is cropped.

Review question

Question (select to reveal the answer)

sns.relplot(data=d, x=..., y=..., ax=ax) gives a warning, and the axes stay empty. Why?

A · relplot needs the data in long form first
B · relplot is figure-level — it creates its own figure and does not accept ax=
C · ax must be passed as the first positional argument
D · plt.figure() must be called beforehand
B. seaborn has two families. Axes-level functions (scatterplot, boxplot, histplot) draw onto a supplied axes. Figure-level ones (relplot, displot, catplot) build and own their whole figure — which is what lets them facet with col=. Use scatterplot(..., ax=ax), or drop ax= and use g.fig afterwards.
Review question

Question (select to reveal the answer)

Completion rates across regions run from 65.6% to 92.0%. What is the effect of ax.set_ylim(0.6, 0.95) on a bar chart?

A · Zoomed in appropriately so the differences are visible
B · Exaggerated the differences — a bar encodes length, so truncating the axis misstates every ratio
C · Nothing, as long as the axis is labelled
D · Improved it, since starting at zero wastes space
B. The real spread is 1.4× (92.0/65.6); on that truncated axis the tallest bar appears roughly 5.7× the shortest (0.32 of visible height vs 0.056). Bars must start at zero because their meaning is length. A line chart is different — it encodes position, so a non-zero baseline is legitimate there.
Exercise · 4 min

Population by region: a complete chart

Grouping, charting, labelling and saving form the whole pipeline from a table to a report-ready figure.

Tasks

  1. Predict which region’s bar is longest, and roughly its share.
  2. Select ▶ Run / Edit and run the code.
  3. Remove .sort_values() and run again. What becomes harder to see?

Result on the lecture laptop (select to reveal)

Luzon: 5,173,000 people, 55% of the eight cities’ total (Mindanao 27%, Visayas 18%). Without sorting, the bars follow alphabetical order (Luzon, Mindanao, Visayas), so the ranking must be read off by eye.

by_reg = cities.groupby("region")["pop"].sum().sort_values() share = by_reg / by_reg.sum() print(share.round(3)) ax = by_reg.plot.barh() ax.set_xlabel("Population of the eight cities") ax.set_title(f"Luzon's three cities hold {share['Luzon']:.0%} of the people") plt.show()
  • .sort_values()smallest first, so the longest bar sits on top
  • f"… {share['Luzon']:.0%} …"the title states the finding, computed from the data
Review question

Question (select to reveal the answer)

A bar chart's y-axis starts at 90 instead of 0. What is the risk?

A · nothing — it saves space
B · it exaggerates small differences
C · the bars vanish
D · colours break

B — it exaggerates small differences.

Bar length encodes value, so a cropped baseline makes a tiny gap look huge. Bars must start at zero; a line chart may crop, since it encodes position, not length.

This week's lab

Four labelled charts

The lab builds a line, bar, scatter and histogram from a real dataset with matplotlib and seaborn, labels each properly and exports one to a file. ~45 minutes.

Lab tasks

plt.subplots, the four chart types, axis labels, and sns one-liners.

The in-browser lab runs matplotlib only (seaborn is not installed there), so the seaborn one-liners are for Colab.

Optional extension

Use plt.subplots(1, 2) to place two charts side by side.

Summary

Building, choosing and labelling charts

Glossary

Terms introduced this week

Building a chart

matplotlib
the basic charting library; every part is drawn explicitly
figure
the whole canvas that is sized and saved
axes
one plotting area inside the figure, on which data are drawn
axis
the x (across) or y (up) number line of an axes
subplot
one of several axes arranged in a grid in one figure
plot
draw data onto an axes; ax.plot joins points with a line
marker
the symbol at each data point ("o", "s")
label
text naming an axis or the chart, with units
legend
the key saying which colour or marker is which series
overplotting
too many dots on top of each other to count
alpha
transparency, from 0 (invisible) to 1 (solid)
dpi
dots per inch: how sharp a saved image is

Choosing and styling

distribution
how one column's values are spread out
histogram
bars counting how many values fall in each bin (range)
relationship
whether two numbers rise or fall together; shown by a scatter
log scale
an axis where each step multiplies (1M, 10M, 100M)
twin axes
a second y scale on the right (twinx); easy to mislead with
seaborn
library on top of matplotlib: statistical charts from a DataFrame
axes-level / figure-level
draws on a given axes (ax=) / builds its own figure
facet
the same chart repeated per group in a grid of panels
hue
seaborn's "colour by this column"
colormap (cmap)
a colour scale that turns numbers into colours
annotate
write a note, with an arrow, on the chart itself
Preparation for next week

Practice & reading

Next Week

Working with data sources

Beyond the CSV: reading JSON and Excel, pulling rows from a SQL database, and fetching live data from a web API.

DS 208 · Programming for Data Science