Enhanced Visualization
Small multiples, color that still works in grayscale, and one interactive chart
Sign in to save your place.
Customize a seaborn chart
Session 13 made one chart. This session changes how that chart is split and labeled. hue colors by a category. col draws one panel per category, which is easier to read than stuffing five series onto one axis.
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
orders = pd.DataFrame({
"month": ["Jan", "Feb", "Mar", "Jan", "Feb", "Mar"],
"region": ["West", "West", "West", "East", "East", "East"],
"orders": [40, 55, 48, 30, 28, 36],
})
sns.set_theme(style="whitegrid", context="notebook")
grid = sns.catplot(
data=orders,
kind="bar",
x="month",
y="orders",
col="region",
color="#7c3aed",
height=3.2,
aspect=1.1,
)
grid.set_axis_labels("Month", "Orders")
grid.figure.savefig("orders_by_region.png", dpi=120)sns.set_theme is the current way to set a style. The older sns.set call still exists, but new code should use set_theme.
Color is not the only channel
About one in twelve men has a color-vision deficiency. Do not encode the only message as red versus green. Add a label, a line pattern, or a direct number. Seaborn's colorblind palette is a start. The title still has to say what the reader should notice.
sns.set_theme(style="whitegrid", palette="colorblind")
fig, ax = plt.subplots(figsize=(6, 4), layout="constrained")
sns.barplot(data=orders, x="month", y="orders", hue="region", ax=ax)
ax.set_title("Orders by month and region")
fig.savefig("orders_colorblind.png", dpi=120)Plotly when the reader should hover
Matplotlib and seaborn write static images. Plotly Express writes an HTML file the reader can hover. Install it only in the project that needs it: uv add plotly. Pandas remains the table. Plotly is the view.
import plotly.express as px
fig = px.bar(
orders,
x="month",
y="orders",
color="region",
barmode="group",
title="Orders by month and region",
)
fig.write_html("orders.html", include_plotlyjs="cdn")What not to ship
A 3D pie chart does not make a two-column table clearer. Start with the bar, line, scatter, histogram, or heatmap from session 13. Add a facet or hover only when the extra channel answers a question the first chart cannot.
Knowledge check
Five regions on one axis have become unreadable. What should you change first?