Lesson 44 · Pandas Full Course
Interactive Charts with Plotly and Pandas (Hover, Animate, Share) | Pandas Course #44
In this lesson you'll be able to: Turn a DataFrame into an interactive chart with plotly.express Shape data with pandas so Plotly can read it Pack four…
- CoursePandas Full Course
- Lesson44 of 65
- FormatJupyter notebook · 39 code cells
- Data1 dataset
What you'll learn
Datasets used in this lesson
Save these next to the notebook. In Google Colab, upload them with the 📁 icon on the left first.
- gapminder.csv preview80.2 KB
📓 Full notebook
Download .ipynbPandas 44: Building Interactive Visuals with Plotly and Pandas#
In this lesson you'll be able to:
- Turn a DataFrame into an interactive chart with plotly.express
- Shape data with pandas so Plotly can read it
- Pack four columns into one bubble chart
- Split charts into panels and animate them over time
- Save charts as HTML and PNG files to share Dataset: Gapminder (data/pandas/gapminder.csv)
Setup: pip install plotly kaleido In this video each chart appears as an image; on your machine you can hover and zoom.
Warm-up: wealth and health#
Lesson 43 measured correlation. One number before we plot.
import pandas as pd
df = pd.read_csv("data/pandas/gapminder.csv")
print(df.shape)
df.head(3)
latest = df[df["year"] == 2007]
pair = latest[["gdpPercap", "lifeExp"]]
print(round(pair.corr(method="spearman").iloc[0, 1], 2))
Your first Plotly chart from a DataFrame#
Problem: a chart readers can explore, not just look at.
import plotly.express as px
japan = df[df["country"] == "Japan"]
fig = px.line(japan, x="year", y="lifeExp", markers=True,
title="Life expectancy in Japan, 1952-2007")
fig.update_layout(xaxis_title="Year",
yaxis_title="Life expectancy (years)")
fig.show()
first, last = japan["lifeExp"].iloc[[0, -1]]
print(round(first, 1), round(last, 1), round(last - first, 1))
picks = ["Japan", "China", "India", "Rwanda", "South Africa"]
five = df[df["country"].isin(picks)]
fig = px.line(five, x="year", y="lifeExp", color="country",
labels={"lifeExp": "Life expectancy", "year": "Year"},
title="Five countries, five different paths")
fig.show()
Quick check: in which year did Rwanda hit its lowest point?
rwanda = df[df["country"] == "Rwanda"].set_index("year")["lifeExp"]
print(rwanda.idxmin(), round(rwanda.min(), 1))
fig = px.line(five, x="year", y="lifeExp", color="country",
hover_data={"pop": ":,", "gdpPercap": ":,.0f"},
title="Hover any point for population and income")
fig.update_layout(xaxis_title="Year",
yaxis_title="Life expectancy (years)")
fig.show()
print(fig.data[0].name, fig.data[0].customdata.shape)
Shape the data with pandas first#
Problem: Plotly needs columns; groupby results hide keys in the index.
by_cont = latest.groupby("continent")["lifeExp"].mean().round(1)
by_cont
Common mistake: plotting a groupby result without reset_index
px.bar(by_cont, x="continent", y="lifeExp")
table = by_cont.reset_index()
fig = px.bar(table, x="continent", y="lifeExp", text_auto=True,
color="continent",
title="Average life expectancy by continent, 2007")
fig.update_layout(xaxis_title="Continent",
yaxis_title="Life expectancy (years)",
showlegend=False)
fig.show()
counts = latest["continent"].value_counts().reset_index()
print(counts.columns.tolist())
fig = px.pie(counts, names="continent", values="count",
title="Countries per continent")
fig.show()
Your turn#
Bar chart of the median GDP per person by continent in 2007.
gdp = latest.groupby("continent")["gdpPercap"].median()
gdp = gdp.round().reset_index()
fig = px.bar(gdp, x="continent", y="gdpPercap", text_auto=True,
title="Median GDP per person by continent, 2007")
fig.update_layout(xaxis_title="Continent",
yaxis_title="GDP per person (US$)")
fig.show()
Bubble charts: four columns in one picture#
Problem: compare wealth, health, size and region at once.
fig = px.scatter(latest, x="gdpPercap", y="lifeExp",
size="pop", color="continent",
hover_name="country", log_x=True, size_max=50,
title="Wealth and health, 2007")
fig.update_layout(xaxis_title="GDP per person (log scale)",
yaxis_title="Life expectancy (years)")
fig.show()
Quick check: which three countries are furthest right?
cols = ["country", "continent", "gdpPercap", "lifeExp"]
latest.nlargest(3, "gdpPercap")[cols].round(1)
latest.nsmallest(3, "lifeExp")[cols].round(1)
Your turn#
Draw the same bubble chart for 1952.
y1952 = df[df["year"] == 1952]
fig = px.scatter(y1952, x="gdpPercap", y="lifeExp", size="pop",
color="continent", hover_name="country",
log_x=True, size_max=50,
title="Wealth and health, 1952")
fig.update_layout(xaxis_title="GDP per person (log scale)",
yaxis_title="Life expectancy (years)")
fig.show()
print(round(y1952["lifeExp"].median(), 1))
print(round(latest["lifeExp"].median(), 1))
Many lines from long data#
Problem: one line per group, built from a tidy table.
keys = ["continent", "year"]
trend = df.groupby(keys, as_index=False)["lifeExp"].mean()
print(trend.shape)
trend.head(3).round(1)
Common mistake: a column name with the wrong capitals
px.line(trend, x="year", y="lifeexp", color="continent")
fig = px.line(trend, x="year", y="lifeExp", color="continent",
markers=True,
title="Average life expectancy by continent")
fig.update_layout(xaxis_title="Year",
yaxis_title="Life expectancy (years)")
fig.show()
wide = trend.pivot(index="year", columns="continent",
values="lifeExp")
fig = px.line(wide, title="Same chart from a wide table")
fig.update_layout(xaxis_title="Year", yaxis_title="Years")
fig.show()
fig = px.line(trend, x="year", y="lifeExp", color="continent",
template="simple_white",
title="Life expectancy by continent, restyled")
fig.update_traces(line_width=3)
fig.update_layout(hovermode="x unified", xaxis_title="Year",
yaxis_title="Life expectancy (years)")
fig.show()
Panels and animation#
Problem: compare groups or years without cramming one chart.
fig = px.histogram(latest, x="lifeExp", facet_col="continent",
nbins=10, title="Life expectancy, 2007")
fig.update_layout(yaxis_title="Countries")
fig.update_xaxes(title_text="Years")
fig.for_each_annotation(lambda a: a.update(text=a.text.split("=")[1]))
fig.show()
latest.groupby("continent")["lifeExp"].agg(["min", "max"]).round(1)
fig = px.scatter(df, x="gdpPercap", y="lifeExp", size="pop",
color="continent", hover_name="country",
animation_frame="year", log_x=True, size_max=50,
range_x=[200, 120000], range_y=[20, 90],
labels={"gdpPercap": "GDP per person",
"lifeExp": "Life expectancy"},
title="Wealth and health, 1952 to 2007")
fig.show()
print(len(fig.frames))
print(fig.frames[0].name, fig.frames[-1].name)
Your turn#
Draw one line chart per continent with facet_col, using trend.
fig = px.line(trend, x="year", y="lifeExp", facet_col="continent",
title="Each continent in its own panel")
fig.update_layout(yaxis_title="Life expectancy (years)")
fig.update_xaxes(title_text="Year")
fig.show()
Save and share: HTML and PNG#
Problem: send an interactive chart to someone without Python.
import os
os.makedirs("output/pandas", exist_ok=True)
html_path = "output/pandas/l44_life_by_continent.html"
fig.write_html(html_path)
print(os.path.exists(html_path))
with open(html_path, encoding="utf-8") as f:
page = f.read()
print(len(page) > 1_000_000)
print("Each continent in its own panel" in page)
png_path = "output/pandas/l44_life_by_continent.png"
fig.write_image(png_path, width=900, height=400)
import matplotlib.pyplot as plt
print(plt.imread(png_path).shape)
Quick check: which file is bigger, the HTML page or the PNG?
html_size = os.path.getsize(html_path)
png_size = os.path.getsize(png_path)
print(html_size > 10 * png_size)
Common mistake: writing into a folder that does not exist
fig.write_html("charts/l44_life.html")
os.makedirs("output/pandas/l44_charts", exist_ok=True)
fig.write_html("output/pandas/l44_charts/l44_life.html")
print(os.path.exists("output/pandas/l44_charts/l44_life.html"))
Mini-project: who caught up?#
Measure each continent's gap to Europe in 1952 and in 2007.
gap = wide.sub(wide["Europe"], axis=0)
gap = gap.drop(columns=["Europe", "Oceania"])
gap.loc[[1952, 2007]].round(1)
closed = (gap.loc[2007] - gap.loc[1952]).round(1)
closed.sort_values(ascending=False)
bars = closed.rename("years").reset_index()
fig = px.bar(bars, x="continent", y="years", text_auto=True,
title="Years of the gap closed, 1952 to 2007")
fig.update_layout(xaxis_title="Continent",
yaxis_title="Years closed")
fig.show()
long_gap = gap.reset_index().melt(id_vars="year",
var_name="continent",
value_name="gap")
fig = px.line(long_gap, x="year", y="gap", color="continent",
markers=True, title="Life expectancy gap to Europe")
fig.add_hline(y=0, line_dash="dash")
fig.update_layout(xaxis_title="Year",
yaxis_title="Years behind Europe")
fig.show()
best = closed.idxmax()
worst = closed.idxmin()
print(f"Most catch-up: {best}, {closed[best]} years")
print(f"Least catch-up: {worst}, {closed[worst]} years")
print(f"{worst} gap in 2007: {gap.loc[2007, worst]:.1f} years")
Recap#
- px.line, px.bar and px.scatter take a DataFrame and column names
- Use reset_index() or as_index=False so keys become columns
- color, size and hover_name pack extra columns into one chart
- facet_col splits panels; animation_frame adds a play button
- write_html shares interactivity; write_image needs Kaleido
Challenges#
- Animated bar chart of average GDP per person by continent.
- Bubble chart of Asia only, 2007, coloured by country.
- Save your favourite chart as both HTML and PNG.
What's next#
Lesson 45: Categorical Data and Memory Optimization Make big tables smaller and faster with the right data types.
Found this useful?
All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.



