Lecture 7: Data Visualisation with matplotlib

BAA1118 - Foundations of Programming for Analytics & AI

Damien Dupré

Summary Statistics Lie

dataset I II III IV
mean x 9.00 9.00 9.00 9.00
mean y 7.50 7.50 7.50 7.50
sd x 3.32 3.32 3.32 3.32
sd y 2.03 2.03 2.03 2.03
r 0.82 0.82 0.82 0.82

Anscombe’s quartet (1973): same means, standard deviations, correlation and best-fit line. Only the plots tell them apart. Always plot the data.

Install the Packages

matplotlib is not part of Python: Colab has it, your own Python does not. Install it once, in a code cell of a VS Code notebook:

%pip install pandas matplotlib seaborn
  • Use %pip, not !pip: %pip installs into the Python that runs your notebook, while !pip can install into a different Python and the import then fails
  • Wait until the cell finishes, then click Restart in the notebook toolbar
  • If a package is already installed, pip says “Requirement already satisfied”, which is fine

Then run the cell on the next slide: no error means it worked.

The gapminder Dataset

Each row is a country in a given year, from 1952 to 2007. As in lecture 6: read it and keep 2007 in g2007.

import pandas as pd
import matplotlib.pyplot as plt         # the plotting library, as plt

url = "https://raw.githubusercontent.com/damien-dupre/data/refs/heads/master/gapminder.csv"
gapminder = pd.read_csv(url)
g2007 = gapminder[gapminder["year"] == 2007]
  • The columns: country, continent, year, lifeExp (in years), pop and gdpPercap (in US dollars)
  • Every chart today starts from gapminder, or from g2007, its 142 countries in 2007

Your Turn: Get Set Up

  1. In VS Code, open your BAA1118 folder, then File -> New File... -> Jupyter Notebook
  2. At the top right, click Select Kernel, then Python Environments…, then the Python that says 3.14
  3. In the first cell, run %pip install pandas matplotlib seaborn. When it has finished, click Restart
  4. In a second cell, run:
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
url = "https://raw.githubusercontent.com/damien-dupre/data/refs/heads/master/gapminder.csv"
gapminder = pd.read_csv(url)
g2007 = gapminder[gapminder["year"] == 2007]
print(g2007.shape)

You should see Python 3.14 at the top right, then (142, 6). Save the notebook in BAA1118 as lecture_7.ipynb. Keep it open: today’s exercises reuse these libraries and gapminder. Done? Help your neighbour.

When It Does Not Work

What you see What to do
No Jupyter Notebook in New File... Install the Python and Jupyter extensions: tutorial 5, step 2
No Python 3.14 in the kernel list Quit VS Code completely and open it again. Still none? Install Python as in tutorial 5, step 1
VS Code asks to install ipykernel Click Install
ModuleNotFoundError Select Python 3.14, run the %pip cell again, then click Restart
CERTIFICATE_VERIFY_FAILED, on a Mac In Applications, open the Python 3.14 folder and double-click Install Certificates.command. Then run the cell again
A network error in the %pip cell Run the cell again
No Python or VS Code on your laptop Follow today in Colab, where these packages are already installed. Then set up with tutorial 5, on Loop

Test 2, on 26 November, runs in a VS Code notebook: fix your setup now, not on the day.

1. Basic Visualisations with matplotlib

Using matplotlib

matplotlib is Python’s main plotting library: pandas, seaborn and most charts written by AI assistants draw with it. A chart is built in layers, one line of code each:

fig, ax = plt.subplots()     # 1. the canvas: an empty frame
ax.scatter(x, y)             # 2. a geometry: what to draw, and which columns
ax.set_xlabel("...")         # 3. more layers: labels, scales, colours
plt.show()                   # 4. show it

Read from top to bottom: each line adds to what the lines above it drew.

The Canvas: fig and ax

fig, ax = plt.subplots(figsize=(8, 1.5))
plt.show()

  • plt.subplots() returns two things, unpacked as in lecture 3: fig, the whole canvas, and ax, the plotting area inside it. figsize: width and height, in inches
  • Only an empty frame: every layer from now on is a method of ax, such as ax.scatter()

Mapping x and y

A geometry’s first two arguments are its mapping: the x column, then the y column.

fig, ax = plt.subplots()
ax.scatter(my_table["my_x_column"], my_table["my_y_column"])   # x first, then y
plt.show()
fig, ax = plt.subplots(figsize=(8, 1.6))
ax.scatter(g2007["gdpPercap"], g2007["lifeExp"])
plt.show()

One point per country in 2007: GDP per capita across, life expectancy up.

More Than x and y

fig, ax = plt.subplots(figsize=(8, 1.6))
ax.scatter(g2007["gdpPercap"], g2007["lifeExp"],
           color="darkred", s=15, marker="s", alpha=0.5)
plt.show()

  • color: a name or a code, such as "#C44E52". s: the size. marker: the shape, "o", "s" or "^". alpha: 0 is invisible, 1 solid, so overlaps show darker
  • Each is one value for the whole layer: section 2 colours by continent

Geometries

Each kind of chart has its own ax method, its geometry:

Method Draws To show
ax.scatter(x, y) points how two columns relate
ax.plot(x, y) a line a change over time
ax.bar(x, heights) bars one number per category
ax.barh(y, widths) sideways bars the same, for long names
ax.hist(values) a histogram how one column is spread
ax.boxplot(groups) boxes the spread in each group

The question picks the geometry. All the others: plot types.

Line Chart

ireland = gapminder[gapminder["country"] == "Ireland"]
fig, ax = plt.subplots(figsize=(8, 1.8))
ax.plot(ireland["year"], ireland["lifeExp"], marker="o")
plt.show()

  • A line joins the rows in order: keep one country first, or it zigzags through all 142
  • marker="o" adds a dot for each year: Ireland, from 67 years in 1952 to 79 in 2007

Bar Chart

means = g2007.groupby("continent")["lifeExp"].mean()
fig, ax = plt.subplots(figsize=(8, 1.8))
ax.bar(means.index, means.values)
plt.show()

  • groupby() gives one mean per continent, with the continents as the index (lecture 6): means.index gives the x positions, means.values the heights
  • A bar’s length is its value, so the axis starts at 0

Histogram

fig, ax = plt.subplots(figsize=(8, 1.8))
ax.hist(g2007["lifeExp"], bins=20, edgecolor="white")
plt.show()

  • One column only: matplotlib cuts it into 20 bins and counts the countries in each
  • 83 countries are above 70 years, and a tail runs down to 40. Try several bins: too few hide the shape, too many turn it into noise

Boxplot

africa = g2007[g2007["continent"] == "Africa"]
europe = g2007[g2007["continent"] == "Europe"]
fig, ax = plt.subplots(figsize=(8, 1.8))
ax.boxplot([africa["lifeExp"], europe["lifeExp"]], tick_labels=["Africa", "Europe"])
plt.show()

  • A list of columns, one box each, named by tick_labels
  • Line: the median. Box: the middle 50%. Whiskers: up to 1.5 box-lengths. Dots: outliers

Your Turn: First Charts

Replace each ____, using the comments, then run the cell:

g1952 = gapminder[gapminder["year"] == 1952]
fig, ax = plt.subplots()
ax.____(g1952["lifeExp"], bins=20)                # a histogram, with .hist()
plt.show()
china = gapminder[gapminder["country"] == ____]    # "China", in quotes
fig, ax = plt.subplots()
ax.____(china["year"], china[____])                # a line, with .plot(), of "lifeExp"
plt.show()

You should see two charts: 1952, with two humps, then China’s line, which drops in 1962.

Solution

g1952 = gapminder[gapminder["year"] == 1952]
fig, ax = plt.subplots()
ax.hist(g1952["lifeExp"], bins=20)              # two humps: around 40, and around 65
plt.show()
china = gapminder[gapminder["country"] == "China"]
fig, ax = plt.subplots()
ax.plot(china["year"], china["lifeExp"])        # 1962: the Great Leap Forward famine
plt.show()

2. Advanced Visualisations with matplotlib

Grey Everything, Colour One Thing

eq_guinea = g2007[g2007["country"] == "Equatorial Guinea"]
fig, ax = plt.subplots(figsize=(8, 1.7))
ax.scatter(g2007["gdpPercap"], g2007["lifeExp"], color="lightgrey")
ax.scatter(eq_guinea["gdpPercap"], eq_guinea["lifeExp"], color="red")
plt.show()

  • Two layers: every country in grey, then Equatorial Guinea in red, on top
  • Bars work the same way: grey bars, then ax.bar() again for the ones to colour

Colour by Group

fig, ax = plt.subplots(figsize=(8, 1.8))
for continent in ["Africa", "Americas", "Asia", "Europe", "Oceania"]:
    subset = g2007[g2007["continent"] == continent]
    ax.scatter(subset["gdpPercap"], subset["lifeExp"], label=continent)
ax.legend()
plt.show()

  • matplotlib colours a layer, not a column: a loop draws one layer per continent
  • label= names each layer, and ax.legend() lists the names

Styles

plt.style.use("petroff10")
fig, ax = plt.subplots(figsize=(8, 1.6))
for continent in ["Africa", "Americas", "Asia", "Europe", "Oceania"]:
    subset = g2007[g2007["continent"] == continent]
    ax.scatter(subset["gdpPercap"], subset["lifeExp"], label=continent)
ax.legend()
plt.show()

  • A style changes every chart after it: petroff10’s colours stay distinct for colour-blind readers. Others: "ggplot", "bmh", "grayscale"

Scales

fig, ax = plt.subplots(figsize=(8, 1.6))
for continent in ["Africa", "Americas", "Asia", "Europe", "Oceania"]:
    subset = g2007[g2007["continent"] == continent]
    ax.scatter(subset["gdpPercap"], subset["lifeExp"], label=continent)
ax.legend()
ax.set_xscale("log")
plt.show()

  • On a log axis every doubling covers the same distance: the curve becomes a line, which lecture 8 fits. ax.set_ylim(0, 90) sets a range

Labels

fig, ax = plt.subplots(figsize=(8, 1.45))
for continent in ["Africa", "Americas", "Asia", "Europe", "Oceania"]:
    subset = g2007[g2007["continent"] == continent]
    ax.scatter(subset["gdpPercap"], subset["lifeExp"], label=continent)
ax.legend()
ax.set_xscale("log")
ax.set(xlabel="GDP per capita (US$, log scale)", ylabel="Life expectancy (years)")
ax.set_title("Each doubling of income comes with a longer life", loc="left")
plt.show()

  • ax.set() sets several labels in one line. The title states the finding

Panels

g1952 = gapminder[gapminder["year"] == 1952]
fig, axes = plt.subplots(1, 2, figsize=(9, 1.6), sharey=True)
axes[0].scatter(g1952["gdpPercap"], g1952["lifeExp"])
axes[0].set(title="1952", xscale="log")
axes[1].scatter(g2007["gdpPercap"], g2007["lifeExp"])
axes[1].set(title="2007", xscale="log")
plt.show()

  • One row of two panels: axes[0] and axes[1], each with its own layers
  • sharey=True: one y-axis for both. Never two y-axes on one panel

Reference Lines

fig, ax = plt.subplots(figsize=(8, 1.8))
ax.hist(g2007["lifeExp"], bins=20, color="lightgrey", edgecolor="white")
ax.axvline(g2007["lifeExp"].mean(), color="red", label="mean")
ax.axvline(g2007["lifeExp"].median(), color="black", label="median")
ax.legend()
plt.show()

  • pandas computes the number, and ax.axvline() draws it as a layer
  • Mean 67, median 72: the tail of short lives pulls the mean down

Saving a Figure

fig.savefig("lifeExp_2007.png", dpi=300, bbox_inches="tight")
  • A relative path: the file appears beside your notebook. To save into a folder, such as "output/lifeExp_2007.png", the folder must already exist
  • dpi=300 for print, 150 for a screen
  • bbox_inches="tight" stops the labels being cut off at the edges
  • .png for documents and slides; .svg or .pdf for anything that will be resized
  • Save with code, never with a right-click: the code is the record of how it was made

Your Turn: One Good Chart

Ireland in 2007. Replace each ____, using the comments:

ireland = g2007[g2007["country"] == "Ireland"]
fig, ax = plt.subplots()
ax.scatter(g2007["gdpPercap"], g2007["lifeExp"], color=____)      # all: "lightgrey"
ax.scatter(ireland["gdpPercap"], ireland["lifeExp"], color=____)  # Ireland: "red"
ax.set(xlabel=____, ylabel=____)               # both labels, each with its unit
ax.set_title(____)                             # a title that states the finding
plt.show()

You should see Ireland in red, at the top right. Then save it, with fig.savefig().

Solution

ireland = g2007[g2007["country"] == "Ireland"]
fig, ax = plt.subplots()
ax.scatter(g2007["gdpPercap"], g2007["lifeExp"], color="lightgrey")
ax.scatter(ireland["gdpPercap"], ireland["lifeExp"], color="red")
ax.set(xlabel="GDP per capita (US$)", ylabel="Life expectancy (years)")
ax.set_title("Ireland: 5th richest country, but 22nd for life expectancy")
plt.show()

3. Combine pandas and matplotlib

A New Column, Then Plot

gapminder["gdp_bn"] = gapminder["pop"] * gapminder["gdpPercap"] / 1_000_000_000
ireland = gapminder[gapminder["country"] == "Ireland"]
fig, ax = plt.subplots(figsize=(8, 1.8))
ax.plot(ireland["year"], ireland["gdp_bn"], marker="o")
ax.set_ylabel("GDP (US$ billions)")
plt.show()

  • pandas first: lecture 6’s gdp_bn, then the filter, once the column exists
  • Then matplotlib draws it like any column: 15 to 167 billion dollars

groupby(), Then Plot

pop_bn = g2007.groupby("continent")["pop"].sum() / 1_000_000_000
pop_bn = pop_bn.sort_values()
fig, ax = plt.subplots(figsize=(8, 1.8))
ax.barh(pop_bn.index, pop_bn.values)
ax.set_xlabel("Population in 2007 (billions)")
plt.show()

  • Sorted: barh() draws from the bottom up, so the largest ends on top
  • Asia: 3.8 billion people, more than the four others together

pivot_table(), Then Plot

by_year = gapminder.pivot_table(index="year", columns="continent",
                                values="lifeExp", aggfunc="mean")
fig, ax = plt.subplots(figsize=(8, 1.45))
by_year.plot(ax=ax, marker="o")
ax.set(xlabel="Year", ylabel="Life expectancy (years)", ylim=(35, 90))
ax.legend(ncol=5)
plt.show()

  • Lecture 6’s table turned round: years as rows, one column per continent
  • pandas’ .plot() draws one line per column, with matplotlib, on your ax

Your Turn: Table to Chart

Replace each ____, using the comments, then run the cell:

medians = g2007.groupby(____)["gdpPercap"].____()   # by "continent", with .median()
medians = medians.____()                              # lowest first, with .sort_values()
fig, ax = plt.subplots()
ax.____(medians.index, medians.values)                # sideways bars, with .barh()
ax.set_xlabel(____)                                   # a label, with its unit
plt.show()

You should see five bars: Africa at the bottom, at about 1,450 dollars, and Oceania on top, at about 29,800.

Solution

medians = g2007.groupby("continent")["gdpPercap"].median()  # incomes are skewed
medians = medians.sort_values()
fig, ax = plt.subplots()
ax.barh(medians.index, medians.values)
ax.set_xlabel("Median GDP per capita in 2007 (US$)")
plt.show()

Same Chart, One Line

import seaborn as sns
fig, ax = plt.subplots(figsize=(8, 2.0))
sns.scatterplot(data=g2007, x="gdpPercap", y="lifeExp", hue="continent", ax=ax)
ax.set(xscale="log", xlabel="GDP per capita (US$, log scale)",
       ylabel="Life expectancy (years)")
plt.show()

  • seaborn takes the whole table in data=, and the columns by name
  • hue="continent" replaces the loop; ax=ax draws on your ax

What seaborn Computes For You

Function Draws Watch out
sns.histplot a histogram it chooses the bins
sns.boxplot a box per group
sns.scatterplot the points
sns.barplot the mean per group error bars: errorbar=None
sns.lineplot the mean per x value a band: errorbar=None

seaborn summarises before it draws, as pandas did in this section. If you cannot say what it computed, you cannot defend the chart.

4. Vibe Coding Visualisations

What Is Vibe Coding?

Describe the chart in plain English, and an AI assistant writes the code.

1. The prompt: “With pandas and matplotlib, using fig, ax: a scatter of gdpPercap against lifeExp from the DataFrame g2007, on a log x-axis, with labels and a title.”

2. The code it writes:

fig, ax = plt.subplots(figsize=(8, 5))
ax.scatter(g2007["gdpPercap"], g2007["lifeExp"], alpha=0.7)
ax.set_xscale("log")
ax.set(xlabel="GDP per capita (US$, log scale)", ylabel="Life expectancy (years)")
ax.set_title("Life Expectancy vs GDP per Capita")
plt.show()

3. Read every line, then run it: its title only names the columns.

Check Before You Trust

Ask for:

  • matplotlib, with fig, ax
  • the table, and its columns
  • the geometry
  • labels and a title

Then check:

  • ax., or plt. everywhere?
  • do the columns exist?
  • labels with units?
  • a mean you did not ask for?

You may use an assistant’s code if you can explain every line of it. A KeyError names a column that does not exist: life_exp instead of lifeExp, for example.

Your Turn: Ask, Then Check

  1. Ask an AI assistant: “With pandas and matplotlib, using fig, ax: from a DataFrame called gapminder, with the columns country, continent, year, lifeExp, pop and gdpPercap, one line per continent of the mean lifeExp in each year, with labels and a title that states the finding.”
  2. Paste its code in a new cell, below the cell that reads gapminder, then check it with the last slide’s list before you run it

You should see the chart of pivot_table(), Then Plot. If not, what did you fix?

References

Thanks for your attention and don’t hesitate to ask if you have any questions!

@damien_dupre

@damien-dupre

https://damien-dupre.github.io

damien.dupre@dcu.ie