5.3. Pandas Plot Styling#
A chart that runs is not yet a chart that works. This section covers three layers of finishing: the look of a chart (style sheets, colors, sizes), keeping the chart honest so it does not exaggerate or hide differences, and making the chart say one clear thing to a busy reader.
5.3.1. Styling Options#
5.3.1.1. Plotting Styles#
matplotlib offers a range of pre-configured plotting styles. Setting the style can be used to easily give plots the general look that you want. To set the style, the syntax is:
matplotlib.style.use(my_plot_style)
To check the aviaible style in the environment, use
plt.style.available
Uncomment/comment the following styles one by one to see the style effect.
plt.style.use("default") ### reset to default style
# plt.style.use("ggplot")
# plt.style.use("bmh")
# plt.style.use("classic")
# plt.style.use("seaborn-v0_8-muted")
np.random.seed(42) ### for reproducibility
df_test = pd.DataFrame({'values': [np.random.randint(0, 100) for num in range(10)]})
df_test.plot.bar(figsize=(4, 3), fontsize=7);
plt.title("Bar Plot with Style", fontsize=10);
plt.legend(fontsize=7, loc="best", bbox_to_anchor=(1, 1));
plt.tick_params(axis='x', rotation=0)
plt.tight_layout()
5.3.1.2. Color Maps#
You can use c to color based off another column value.
Use cmap to indicate colormap to use.
For all the colormaps, check out: http://matplotlib.org/users/colormaps.html
tips = sns.load_dataset("tips")
ax = tips.plot(
kind="scatter",
x="total_bill", y="tip",
c="size", # column to map to color
colormap="viridis",
figsize=(5, 3),
alpha=0.7,
fontsize=8,
title="Tips vs Total Bill — colored by party size"
)
plt.tight_layout()
Different colormaps can be used for different presentation effects. To see the available colormaps, use the syntax:
plt.colormaps()
fig, axes = plt.subplots(1, 3, figsize=(12, 3))
for ax, cmap in zip(axes, ["viridis", "coolwarm", "RdYlGn"]):
tips.plot(
kind="scatter",
x="total_bill", y="tip",
c="size",
colormap=cmap,
alpha=0.7,
fontsize=8,
ax=ax,
title=cmap
)
plt.tight_layout()
Pick the kind of colormap from what the colored values mean:
Colormap kind |
Values it fits |
Business example |
Colormaps to try |
|---|---|---|---|
Sequential |
Ordered values from low to high |
Sales level by store, party size |
|
Diverging |
Values above or below a meaningful middle, such as zero or a target |
Change vs. last year, actual minus target |
|
Categorical (qualitative) |
Groups with no order |
Regions, product categories |
|
Party size above is ordered from small to large, so a sequential map such as viridis fits it best; coolwarm and RdYlGn suggest a meaningful middle that party size does not have. viridis is also a safe default for readers: it changes evenly in brightness, so it still reads for color-blind viewers and in grayscale. Red-green maps such as RdYlGn are hard to read for the many people with red-green color blindness.
5.3.1.3. Size#
Or use s to indicate size based off another column. s parameter needs to be an array, not just the name of a column:
tips = sns.load_dataset("tips")
ax = tips.plot(
kind="scatter",
x="total_bill",
y="tip",
s=tips["size"] * 20,
figsize=(4, 3),
alpha=0.5,
fontsize=8,
title="Tips vs Total Bill"
)
ax.set_xlabel("Total Bill ($)")
ax.set_ylabel("Tip ($)")
plt.tight_layout()
### Exercise: Size-Encoded Scatter
# Goal: Add a third variable using marker size.
# Requirements:
# 1) Plot `A` vs `B` from `df1`.
# 2) Use point size based on `abs(C) * 60`.
# 3) Set `alpha=0.5` so overlap stays readable.
# Stretch: Compare size encoding to color encoding and note tradeoffs.
### Your code starts here.
### Your code ends here.
5.3.2. Honest Charts#
A chart can show correct numbers and still mislead. The usual causes are an axis that starts in the wrong place, panels drawn on different scales, and shapes that the eye cannot measure. The rules below keep a chart honest.
5.3.2.1. Bars Start at Zero#
A bar’s length stands for its value, so the reader compares lengths. If the value axis starts above zero (a truncated axis), the lengths no longer match the values and small differences look huge. The scores below for four regions differ by at most 7 points out of 100.
scores = pd.DataFrame({
"region": ["North", "South", "East", "West"],
"satisfaction": [81, 84, 79, 86], ### customer satisfaction, 0-100
})
fig, axes = plt.subplots(1, 2, figsize=(8, 2.8))
scores.plot.bar(x="region", y="satisfaction", ax=axes[0], ylim=(76, 88),
legend=False, rot=0, fontsize=8, title="Misleading: axis starts at 76")
scores.plot.bar(x="region", y="satisfaction", ax=axes[1], ylim=(0, 100),
legend=False, rot=0, fontsize=8, title="Honest: axis starts at 0")
for ax in axes:
ax.set_xlabel("")
ax.set_ylabel("Satisfaction (0-100)")
plt.tight_layout()
On the left, West’s bar looks about three times as tall as East’s (10 units above the axis floor versus 3), although the scores are 86 and 79. On the right, the bars are almost the same height, which is the honest picture. Pandas starts bar charts at zero by default; the problem appears when someone sets ylim to “zoom in.”
5.3.2.2. Line Charts May Zoom In#
A line chart shows values by the position of points, not by length, so its axis does not have to start at zero. Zooming in is often the right choice, because it shows the ups and downs the question is about. Pandas zooms line charts in by default. Label the axis so the reader sees where it starts.
monthly_rev = sales.groupby("month")["revenue"].sum() / 1000
fig, axes = plt.subplots(1, 2, figsize=(9, 2.8))
monthly_rev.plot(ax=axes[0], fontsize=8, title="Zoomed in (pandas default)")
monthly_rev.plot(ax=axes[1], fontsize=8, ylim=(0, 700), title="Axis from zero")
for ax in axes:
ax.set_xlabel("Month")
ax.set_ylabel("Revenue ($K)")
plt.tight_layout()
Both charts are honest because both axes are labeled. The zoomed-in chart shows the December peaks and the growth from 2024 to 2025 more clearly, so it fits a trend question better.
5.3.2.3. Same Scale When Comparing#
When several panels are compared side by side, draw them on the same scale. With subplots=True, pandas gives each panel its own y-axis by default, so a small region can look as big as a large one. sharey=True puts every panel on the same y-axis.
region_monthly = sales.groupby(["month", "region"])["revenue"].sum().unstack() / 1000
region_monthly.plot(subplots=True, layout=(1, 4), figsize=(10, 2.5),
fontsize=7, legend=False, title=list(region_monthly.columns),
xticks=[], xlabel="");
plt.suptitle("Own scale per panel: East looks as large as South", fontsize=10)
plt.tight_layout()
region_monthly.plot(subplots=True, layout=(1, 4), figsize=(10, 2.5), sharey=True,
fontsize=7, legend=False, title=list(region_monthly.columns),
xticks=[], xlabel="");
plt.suptitle("Shared scale (sharey=True): South is clearly the largest", fontsize=10)
plt.tight_layout()
In the first row each panel stretches its own region’s line to fill the box, so the four regions look about the same size. In the second row they share one y-axis, and South’s line sits clearly higher than East’s. When you need separate charts instead of subplots, give them the same ylim.
5.3.2.4. Avoid 3-D and Crowded Pies#
People judge position and length accurately, and angle and area poorly. Bar and line charts use position and length; pie charts use angle and area. A pie works for two or three parts with clearly different sizes. With more parts or close sizes, readers cannot rank the slices, as the regional shares of revenue below show. 3-D effects make it worse: tilting a pie or adding depth to bars distorts the angles and lengths, so slices and bars in front look bigger than they are. Pandas has no 3-D option, and that is a good thing.
region_share = (sales.groupby("region")["revenue"].sum()
/ sales["revenue"].sum() * 100).sort_values()
print(region_share.round(1))
fig, axes = plt.subplots(1, 2, figsize=(8, 3))
region_share.plot.pie(ax=axes[0], fontsize=8, ylabel="",
title="Pie: which is bigger, North or West?")
region_share.plot.barh(ax=axes[1], fontsize=8, xlabel="Share of revenue (%)",
ylabel="", title="Bar: the ranking is easy to read")
plt.tight_layout()
region
East 21.8
North 24.4
West 25.5
South 28.3
Name: revenue, dtype: float64
In the pie, North (24.4%) and West (25.5%) look the same size. In the bar chart, the order is plain at a glance.
### Exercise: Fix a Misleading Bar Chart
# The chart below makes phone orders look far smaller than online orders.
# 1) Run the code and note how big the differences look.
# 2) Redraw the chart so the y-axis starts at zero (for example `ylim=(0, 60)`).
# 3) Turn off the legend, label the y-axis "Average order value ($)", and
# keep the title "Average Order Value by Channel".
import pandas as pd
orders = pd.DataFrame({
"channel": ["Online", "In store", "Phone"],
"avg_order": [52, 49, 46],
})
orders.plot.bar(x="channel", y="avg_order", ylim=(45, 53), rot=0,
title="Average Order Value by Channel");
### Your code starts here.
### Your code ends here.
5.3.3. Charts That Communicate#
A report chart should tell the reader one thing within a few seconds. A few small changes turn a default chart into one that does:
Title with the finding, not the topic. “Sales by Region” names the topic; “West was the only region whose Q3 revenue fell” states the finding, called a takeaway title. Write the title last, after you have read the chart.
Label axes with units, such as “Revenue ($K)” or “Change vs. Q3 2024 (%)”.
Sort bars by value with
sort_values()before plotting, so the ranking reads in order.Highlight the bar that matters and grey out the rest with a list of colors, one per bar.
Add a reference line for a target or an average.
Drop the legend when there is only one series; the title and axis label already say what the bars are.
The example uses third-quarter (July-September) revenue by region for 2024 and 2025, totaled from retail_daily_sales.csv and rounded to thousands of dollars. Section 5.4 shows how to compute quarter totals from dates.
q3 = pd.DataFrame({
"region": ["North", "South", "East", "West"],
"q3_2024": [247.5, 282.3, 226.6, 258.3], ### Q3 revenue ($K)
"q3_2025": [273.5, 309.7, 247.9, 243.6],
}).set_index("region")
q3["change"] = (q3["q3_2025"] / q3["q3_2024"] - 1) * 100 ### percent change
print(q3.round(1))
q3.plot.bar(y="change", figsize=(4, 3), title="Q3 Revenue Change by Region");
q3_2024 q3_2025 change
region
North 247.5 273.5 10.5
South 282.3 309.7 9.7
East 226.6 247.9 9.4
West 258.3 243.6 -5.7
The default chart is correct but makes the reader do the work: the bars are in no particular order, the y-axis has no unit, the legend repeats the column name, and the title names only the topic. The finding is in the table: West fell 5.7% while the other regions grew 9.4% to 10.5%.
The improved chart applies the six steps. plot() returns the chart’s axes (an Axes object), and ax.axhline() draws a horizontal line across it at a given y value. It is the one Matplotlib method used in this chapter; Chapter 6 covers Matplotlib in full.
change = q3["change"].sort_values() ### 3) sort bars
colors = ["tab:red" if region == "West" else "lightgray" ### 4) highlight West
for region in change.index]
chain_change = (q3["q3_2025"].sum() / q3["q3_2024"].sum() - 1) * 100
print(f"Chain-wide Q3 change: {chain_change:.1f}%")
ax = change.plot.bar(
color=colors, rot=0, figsize=(5, 3), fontsize=8,
xlabel="",
ylabel="Change vs. Q3 2024 (%)", ### 2) units
title="West was the only region whose Q3 revenue fell", ### 1) finding
) ### 6) a Series has no legend
ax.axhline(chain_change, color="black", linestyle="--", linewidth=1) ### 5) reference line
ax.axhline(0, color="black", linewidth=0.8)
plt.tight_layout()
Chain-wide Q3 change: 5.9%
The reader now sees the answer first: one red bar below zero, three grey bars above the dashed line at the chain-wide change of 5.9%. Plotting the change Series rather than the DataFrame column also drops the legend, since a Series has only one set of values.
### Exercise: From Default to Report-Ready
# A manager wants one chart for a report on revenue by product category.
# The default chart is drawn below.
# 1) Sort the categories by revenue.
# 2) Highlight Electronics in one color and draw the other bars in light gray.
# 3) Label the y-axis "Revenue ($K)" and remove the x-axis label.
# 4) Add a dashed reference line at the average category revenue with `ax.axhline()`.
# 5) Write a takeaway title. Hint: what share of total revenue is Electronics?
cat_rev = sales.groupby("category")["revenue"].sum() / 1000
cat_rev.to_frame().plot.bar(title="Revenue by Category");
### Your code starts here.
### Your code ends here.
Electronics share of revenue: 43%