| 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 |
BAA1118 - Foundations of Programming for Analytics & AI
| 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.
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, not !pip: %pip installs into the Python that runs your notebook, while !pip can install into a different Python and the import then failsThen run the cell on the next slide: no error means it worked.
Each row is a country in a given year, from 1952 to 2007. As in lecture 6: read it and keep 2007 in g2007.
country, continent, year, lifeExp (in years), pop and gdpPercap (in US dollars)gapminder, or from g2007, its 142 countries in 2007BAA1118 folder, then File -> New File... -> Jupyter Notebook%pip install pandas matplotlib seaborn. When it has finished, click RestartYou 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.
| 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.
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:

Read from top to bottom: each line adds to what the lines above it drew.
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 inchesax, such as ax.scatter()A geometry’s first two arguments are its mapping: the x column, then the y column.

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

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 darkerEach 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.

marker="o" adds a dot for each year: Ireland, from 67 years in 1952 to 79 in 2007
groupby() gives one mean per continent, with the continents as the index (lecture 6): means.index gives the x positions, means.values the heights
bins: too few hide the shape, too many turn it into noise
tick_labelsReplace 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.
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()


ax.bar() again for the ones to colour
label= names each layer, and ax.legend() lists the names
petroff10’s colours stay distinct for colour-blind readers. Others: "ggplot", "bmh", "grayscale"
ax.set_ylim(0, 90) sets a rangefig, 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 findingg1952 = 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()
axes[0] and axes[1], each with its own layerssharey=True: one y-axis for both. Never two y-axes on one panel
ax.axvline() draws it as a layer"output/lifeExp_2007.png", the folder must already existdpi=300 for print, 150 for a screenbbox_inches="tight" stops the labels being cut off at the edges.png for documents and slides; .svg or .pdf for anything that will be resizedIreland 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().
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()

gdp_bn, then the filter, once the column exists
barh() draws from the bottom up, so the largest ends on top
.plot() draws one line per column, with matplotlib, on your axReplace each ____, using the comments, then run the cell:
You should see five bars: Africa at the bottom, at about 1,450 dollars, and Oceania on top, at about 29,800.

data=, and the columns by namehue="continent" replaces the loop; ax=ax draws on your ax| 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.
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:
3. Read every line, then run it: its title only names the columns.
Ask for:
fig, axThen check:
ax., or plt. everywhere?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.
gapminder, then check it with the last slide’s list before you run itYou should see the chart of pivot_table(), Then Plot. If not, what did you fix?
fig, ax and the ax methods
Thanks for your attention and don’t hesitate to ask if you have any questions!