Lesson 42 · Pandas Full Course
Pandas + Matplotlib + Seaborn: Make Professional Charts in Python | Pandas Course #42
In this lesson you'll be able to: Take control of any pandas chart through its Matplotlib axes Put several pandas charts side by side in one figure Hand a…
- CoursePandas Full Course
- Lesson42 of 65
- FormatJupyter notebook · 38 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.
📓 Full notebook
Download .ipynbPandas 42: Integrating Pandas with Matplotlib and Seaborn#
In this lesson you'll be able to:
- Take control of any pandas chart through its Matplotlib axes
- Put several pandas charts side by side in one figure
- Hand a DataFrame straight to Seaborn and colour by a column
- Mix Seaborn and Matplotlib: reference lines, notes, themes
- Save a finished figure to a file and check it Dataset: restaurant tips (data/pandas/tips.csv)
Warm-up: a quick pandas chart#
Lesson 41 drew line, bar, histogram and box plots with pandas.
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv("data/pandas/tips.csv")
print(df.shape)
df.head()
df["total_bill"].plot(kind="hist", bins=20, edgecolor="black")
plt.title("Distribution of total bills")
plt.xlabel("Total bill ($)")
plt.ylabel("Number of bills")
plt.show()
Every pandas chart is a Matplotlib chart#
Problem: style and adjust a pandas chart beyond its own options.
ax = df["tip"].plot(kind="hist", bins=20)
print(type(ax))
ax = df["tip"].plot(kind="hist", bins=20, color="teal")
ax.set_title("Most tips are between 2 and 4 dollars")
ax.set_xlabel("Tip ($)")
ax.set_ylabel("Number of bills")
ax.axvline(df["tip"].median(), color="black", linestyle="--")
plt.show()
print(df["tip"].median())
print((df["tip"].between(2, 4)).mean().round(2))
Common mistake: a scatter plot with only one column
df.plot(kind="scatter", x="total_bill")
ax = df.plot(kind="scatter", x="total_bill", y="tip", alpha=0.6)
ax.set_title("Bigger bills, bigger tips")
ax.set_xlabel("Total bill ($)")
ax.set_ylabel("Tip ($)")
plt.show()
Quick check: how strongly do bill and tip move together?
print(round(df["total_bill"].corr(df["tip"]), 2))
Several charts in one figure#
Problem: compare two views side by side instead of scrolling.
- A figure is the whole canvas
- Each axes is one chart drawn on it
fig, (left, right) = plt.subplots(1, 2, figsize=(10, 4))
df["total_bill"].plot(kind="hist", bins=20, ax=left)
df["tip"].plot(kind="hist", bins=20, ax=right, color="teal")
left.set_title("Total bill ($)")
right.set_title("Tip ($)")
fig.tight_layout()
plt.show()
day_order = ["Thur", "Fri", "Sat", "Sun"]
counts = df["day"].value_counts().reindex(day_order)
avg_tip = df.groupby("day")["tip"].mean().reindex(day_order)
print(counts.to_dict())
print(avg_tip.round(2).to_dict())
fig, axes = plt.subplots(1, 2, figsize=(10, 4), sharex=True)
counts.plot(kind="bar", ax=axes[0], rot=0, color="grey")
avg_tip.plot(kind="bar", ax=axes[1], rot=0, color="teal")
axes[0].set(title="Bills per day", xlabel="Day", ylabel="Bills")
axes[1].set(title="Average tip", xlabel="Day", ylabel="Tip ($)")
fig.tight_layout()
plt.show()
Quick check: Friday has the fewest bills. Is its average tip the lowest?
print(avg_tip.idxmin(), round(avg_tip.min(), 2))
Hand the DataFrame to Seaborn#
Problem: colour and split a chart by a category without loops.
import seaborn as sns
ax = sns.histplot(data=df, x="total_bill", bins=20, kde=True)
ax.set(title="Total bills with a smooth density curve",
xlabel="Total bill ($)", ylabel="Number of bills")
plt.show()
ax = sns.scatterplot(data=df, x="total_bill", y="tip",
hue="time", alpha=0.7)
ax.set(title="Tips against bills, lunch and dinner",
xlabel="Total bill ($)", ylabel="Tip ($)")
plt.show()
df.groupby("time")["total_bill"].agg(["size", "mean"]).round(2)
ax = sns.regplot(data=df, x="total_bill", y="tip",
scatter_kws={"alpha": 0.5})
ax.set(title="Each extra dollar of bill adds about 10 cents",
xlabel="Total bill ($)", ylabel="Tip ($)")
plt.show()
import numpy as np
slope, intercept = np.polyfit(df["total_bill"], df["tip"], 1)
print(round(slope, 3), round(intercept, 2))
Common mistake: a column name Seaborn cannot find
sns.boxplot(data=df, x="day", y="full_bill")
ax = sns.boxplot(data=df, x="day", y="total_bill", order=day_order)
ax.set(title="Weekend bills run higher",
xlabel="Day", ylabel="Total bill ($)")
plt.show()
Compare groups: pandas numbers, Seaborn pictures#
Problem: show a grouped average, and how much it varies.
by_group = df.groupby(["sex", "smoker"])["tip"].mean()
by_group.round(2)
ax = sns.barplot(data=df, x="sex", y="tip", hue="smoker",
errorbar=None)
ax.set(title="Average tip by sex and smoker",
xlabel="Sex", ylabel="Average tip ($)")
plt.show()
ax = sns.barplot(data=df, x="day", y="tip", order=day_order,
errorbar=("ci", 95), color="teal")
ax.set(title="Average tip by day, with 95% intervals",
xlabel="Day", ylabel="Average tip ($)")
plt.show()
Your turn#
Draw a violin plot of tip by time, split by smoker.
ax = sns.violinplot(data=df, x="time", y="tip", hue="smoker",
split=True)
ax.set(title="Tip by meal time and smoker",
xlabel="Meal", ylabel="Tip ($)")
plt.show()
df.groupby(["time", "smoker"])["tip"].median()
Mix both libraries: themes, notes and reference lines#
Problem: make a chart presentation-ready, not just correct.
sns.set_theme(style="whitegrid")
df["tip_pct"] = 100 * df["tip"] / df["total_bill"]
print(df["tip_pct"].describe().round(1))
ax = sns.boxplot(data=df, x="day", y="tip_pct", order=day_order)
ax.axhline(15, color="red", linestyle="--")
ax.annotate("71% tip on a $7.25 bill", xy=(3, 71), xytext=(1.2, 60),
arrowprops={"arrowstyle": "->", "color": "black"})
ax.set(title="Tip percentage by day",
xlabel="Day", ylabel="Tip (% of bill)")
plt.show()
top = df.nlargest(1, "tip_pct")
top[["total_bill", "tip", "day", "tip_pct"]].round(2)
with sns.axes_style("darkgrid"):
ax = sns.countplot(data=df, x="day", hue="smoker",
order=day_order)
ax.set(title="Bills by day and smoker",
xlabel="Day", ylabel="Bills")
plt.show()
pd.crosstab(df["day"], df["smoker"]).reindex(day_order)
Quick check: on which day do smokers outnumber non-smokers?
table = pd.crosstab(df["day"], df["smoker"])
table[table["Yes"] > table["No"]]
Save a figure and check it#
Problem: get a chart into a report, a slide or an email.
import os
os.makedirs("output/pandas", exist_ok=True)
fig, ax = plt.subplots(figsize=(6, 4))
sns.histplot(data=df, x="tip", bins=15, ax=ax, color="purple")
ax.set(title="Tips", xlabel="Tip ($)", ylabel="Bills")
fig.tight_layout()
fig.savefig("output/pandas/l42_tips_hist.png", dpi=100)
plt.close(fig)
img = plt.imread("output/pandas/l42_tips_hist.png")
print(img.shape)
Common mistake: saving to a folder that does not exist
fig.savefig("reports/l42_tips.png")
os.makedirs("output/pandas/l42_reports", exist_ok=True)
fig.savefig("output/pandas/l42_reports/l42_tips.png", dpi=100)
print(os.path.exists("output/pandas/l42_reports/l42_tips.png"))
Mini-project: do weekend diners tip better?#
Plan: label the days, compare dollars, then compare percentages.
weekend = df["day"].isin(["Sat", "Sun"])
df["day_type"] = weekend.map({True: "Weekend", False: "Weekday"})
cols = ["tip", "total_bill", "tip_pct"]
summary = df.groupby("day_type")[cols].mean().round(2)
summary
fig, (left, right) = plt.subplots(1, 2, figsize=(10, 4))
summary["tip"].plot(kind="bar", ax=left, rot=0, color="teal")
sns.boxplot(data=df, x="day_type", y="tip_pct", ax=right,
order=["Weekday", "Weekend"])
left.set(title="Average tip ($)", xlabel="", ylabel="Tip ($)")
right.set(title="Tip as % of bill", xlabel="", ylabel="%")
right.axhline(15, color="red", linestyle="--")
fig.tight_layout()
plt.show()
df.groupby("day_type")["tip_pct"].median().round(2)
gap = summary.loc["Weekend"] - summary.loc["Weekday"]
print(f"Extra tip: ${gap['tip']:.2f}")
print(f"Extra bill: ${gap['total_bill']:.2f}")
print(f"Change in tip share: {gap['tip_pct']:.2f} points")
Recap#
- pandas .plot() returns a Matplotlib axes: keep it as ax
- plt.subplots() plus ax= puts several charts in one figure
- Seaborn takes data=df and column names; hue splits by category
- Add axhline, annotate and themes with Matplotlib and Seaborn
- fig.savefig() writes a file, into a folder that must exist
Challenges#
- Two side-by-side charts: bills per party size and avg tip_pct.
- Seaborn scatter of tip_pct against total_bill, coloured by day.
- Save your favourite chart to output/pandas and read it back.
What's next#
Lesson 43: Data Correlation and Heatmaps Measure how columns move together and map it all in one picture.
Found this useful?
All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.



