5.2. Pandas Chart Types#
A chart is an answer to a question. This section starts with the questions managers ask about sales and the chart that fits each kind of question. Then it tours the common pandas chart types one at a time, with a note on when each one works and when it misleads.
5.2.1. Start with the Question#
Before you pick a chart, say what kind of question the chart has to answer. Most business questions fall into one of five types, and each type has a chart to try first.
Question type |
What it asks |
Example manager question |
First chart to try |
|---|---|---|---|
Comparison |
How do categories rank against each other? |
Which region brings in the most revenue? |
Bar (horizontal when labels are long) |
Trend |
How does a number change over time? |
How did monthly revenue change over two years? |
Line |
Distribution |
What values are typical, and how spread out are they? |
What does a typical day’s revenue look like? Any unusual days? |
Histogram, box plot |
Relationship |
Do two numbers move together? |
Do regions that spend more on ads sell more? |
Scatter (hexbin when points pile up) |
Part of a whole |
How is a total split into pieces? |
How much of each region’s revenue comes from each category? |
Stacked bar (pie only for 2-3 parts) |
Section Pandas Plotting Basics has the full reference table of plot types and the Abela chart chooser. This table is a shortcut for the five questions you will meet most often.
5.2.1.1. Four Questions, Four Charts#
The examples in this section use retail_daily_sales.csv, simulated daily sales for a retail chain over 2024 and 2025. Each row is one day, one region (North, South, East, West), and one product category (Electronics, Home, Apparel), with the units sold, the revenue, and the ad spend.
The date column is read as text such as "2024-01-15". Its first seven characters, "2024-01", name the month, so one line of code gives each row a month label. Section 5.4 shows how pandas works with real dates.
sales = pd.read_csv(path_data + "retail_daily_sales.csv")
sales["month"] = sales["date"].str[:7] ### "2024-01-15" -> "2024-01"; 5.4 explains dates
print(sales.shape)
sales.head()
(8772, 7)
| date | region | category | units | revenue | ad_spend | month | |
|---|---|---|---|---|---|---|---|
| 0 | 2024-01-01 | North | Electronics | 5 | 589.66 | 99.41 | 2024-01 |
| 1 | 2024-01-01 | North | Home | 14 | 617.12 | 99.41 | 2024-01 |
| 2 | 2024-01-01 | North | Apparel | 26 | 792.02 | 99.41 | 2024-01 |
| 3 | 2024-01-01 | South | Electronics | 15 | 1842.10 | 112.08 | 2024-01 |
| 4 | 2024-01-01 | South | Home | 13 | 599.25 | 112.08 | 2024-01 |
Four managers each bring one question. For each one, name the question type, summarize the data with groupby(), and draw the chart that fits.
Comparison. The sales director asks: Which region brings in the most revenue? Regions are categories with no natural order, so a bar chart fits. Sorting the bars makes the ranking easy to read.
region_rev = sales.groupby("region")["revenue"].sum().sort_values() / 1_000_000
region_rev.plot.barh(
figsize=(4, 2.5), fontsize=8,
title="Total Revenue by Region, 2024-2025"
)
plt.xlabel("Revenue ($M)")
plt.ylabel("")
plt.tight_layout()
Answer: South brings in the most revenue, about $2.53 million over the two years, and East the least, about $1.94 million.
Trend. The CFO asks: How did monthly revenue change over the two years? Months are in time order, so a line chart fits.
monthly_rev = sales.groupby("month")["revenue"].sum() / 1000
monthly_rev.plot.line(
figsize=(5, 2.5), fontsize=8, marker="o", markersize=3,
title="Monthly Revenue, 2024-2025"
)
plt.xlabel("Month")
plt.ylabel("Revenue ($K)")
plt.tight_layout()
Answer: revenue grows from 2024 to 2025 and peaks every December, at about $601K in December 2024 and $653K in December 2025.
Distribution. The operations manager asks: What does a typical day’s revenue look like, and are there unusual days? That is a question about the spread of one number, so a histogram fits. First add up the revenue of all regions and categories for each day.
daily_rev = sales.groupby("date")["revenue"].sum() / 1000
daily_rev.plot.hist(
bins=30, edgecolor="white",
figsize=(4, 2.5), fontsize=8,
title="Daily Revenue, 2024-2025"
)
plt.xlabel("Revenue per day ($K)")
plt.ylabel("Number of days")
plt.tight_layout()
print(daily_rev.describe().round(1))
count 731.0
mean 12.2
std 3.2
min 7.1
25% 10.1
50% 11.4
75% 13.1
max 26.7
Name: revenue, dtype: float64
Answer: a typical day brings in about $11K (the median is $11.4K, and the middle half of days fall between $10.1K and $13.1K), and the long tail on the right holds 28 days above $20K, all of them in December.
Relationship. The marketing manager asks: On days when a region spends more on ads, does it sell more? Both ad spend and revenue are numbers, so a scatter plot fits. Each point is one region on one day.
region_day = sales.groupby(["date", "region"])[["ad_spend", "revenue"]].sum()
region_day.plot.scatter(
x="ad_spend", y="revenue",
alpha=0.3, s=8,
figsize=(4, 3), fontsize=8,
title="Ad Spend vs. Revenue (one point per region-day)"
)
plt.xlabel("Ad spend ($)")
plt.ylabel("Revenue ($)")
plt.tight_layout()
Answer: yes, region-days with more ad spend tend to bring in more revenue; the cloud of points rises from left to right. A scatter plot shows that two numbers move together, not that one causes the other: in this data both ad spend and revenue rise in the holiday season.
The fifth type, part of a whole, gets its own example in the stacked bar plot under Common Chart Types below.
5.2.1.2. Common Mistake: Lines Across Categories#
A line connects points in order, so it tells the reader “this changes from one point to the next.” That is true for months, but regions have no order. On the left, the line from East to North to South to West looks like a trend that does not exist; reorder the regions and the “trend” changes. On the right, the bar chart answers the same comparison question honestly.
region_rev_abc = sales.groupby("region")["revenue"].sum() / 1_000_000 ### alphabetical order
fig, axes = plt.subplots(1, 2, figsize=(8, 2.8))
region_rev_abc.plot.line(ax=axes[0], marker="o", fontsize=8,
title="Wrong: line across regions")
region_rev_abc.plot.bar(ax=axes[1], fontsize=8, rot=0,
title="Right: bars for categories")
for ax in axes:
ax.set_xlabel("")
ax.set_ylabel("Revenue ($M)")
plt.tight_layout()
### Exercise: Choose and Draw a Chart
# A store manager asks: "How did the number of units we sell each month
# change over the two years?"
# 1) Print the question type (comparison, trend, distribution,
# relationship, or part of a whole).
# 2) Add up `units` for each `month` in `sales`.
# 3) Draw the chart type that fits, with the title "Monthly Units Sold"
# and the y-axis label "Units".
# Print exactly:
# Question type: trend
### Your code starts here.
### Your code ends here.
Question type: trend
5.2.2. Common Chart Types#
if "np" not in globals():
import numpy as np
if "pd" not in globals():
import pandas as pd
if "plt" not in globals():
import matplotlib.pyplot as plt
if "sns" not in globals():
import seaborn as sns
5.2.2.1. Line Plots#
Use it when the x-axis has a natural order, usually time, and the question is about a trend.
Avoid it when the x-axis holds categories with no order, such as regions or products; use bars.
### Total revenue for each month and category, then one column per category
cat_monthly = sales.groupby(["month", "category"])["revenue"].sum().unstack() / 1000
cat_monthly.plot(
kind="line",
figsize=(5, 3),
fontsize=8,
title="Monthly Revenue by Category",
marker="o", markersize=3 # show data points
)
plt.xlabel("Month")
plt.ylabel("Revenue ($K)")
plt.legend(title="Category", bbox_to_anchor=(1.02, 1), loc="upper left", fontsize=7)
plt.tight_layout()
.unstack() turns the inner group label (category) into columns, so pandas draws one line per column. Electronics brings in the most revenue every month, and all three categories peak in December.
### Exercise: Line Plot Styling
# Goal: Show trend behavior for one feature.
# Requirements:
# 1) Plot `df1['B']` as a line plot.
# 2) Use `figsize=(8, 4)` and `lw=2`.
# 3) Set x-label to "Index" and y-label to "B values".
# Stretch: Overlay a rolling mean with window=10 on the same axes.
### Your code starts here.
### Your code ends here.
5.2.2.2. Histograms#
Use it when the question is about the shape and spread of one numeric column: typical values, range, unusual values.
Avoid it when you need to compare many groups at once (use box plots) or the column is a category (use bars of counts).
daily_units = sales.groupby("date")["units"].sum() ### units sold on each day
# ax = daily_units.plot( ### plot() returns the Axes object,
### so we can capture it in a variable
daily_units.plot(
kind="hist",
figsize=(4, 2.5),
bins=20,
edgecolor="white",
alpha=0.8,
fontsize=7,
title="Distribution of Daily Units Sold"
)
plt.xlabel("Units sold per day")
plt.ylabel("Number of days")
plt.tight_layout()
### Exercise: Histogram Fundamentals
# Goal: Visualize the distribution of `revenue` in `sales`
# (one row is one day, one region, and one category).
# Requirements:
# 1) Plot a histogram for `sales['revenue']` with exactly 50 bins.
# 2) Set `figsize=(8, 4)` and `alpha=0.7`.
# 3) Add a title: "Distribution of Revenue per Row".
# Stretch: Add vertical dashed lines for the mean and median of `revenue`.
### Your code starts here.
### Your code ends here.
5.2.2.3. Scatter Plot#
Use it when the question is whether two numeric columns move together.
Avoid it when thousands of points pile on top of each other (use a hexbin plot) or one of the columns is a category.
tips = sns.load_dataset("tips")
tips.plot(
kind="scatter",
x="total_bill", y="tip",
alpha=0.5, fontsize=7,
title="Basic",
figsize=(4, 3),
s=tips["size"] * 15 ### scale size by 'size' column
);
### Exercise: Scatter Relationship
# Goal: Examine the relationship between `A` and `B`.
# Requirements:
# 1) Create a scatter plot with `x='A'` and `y='B'`.
# 2) Set `figsize=(7, 5)`.
# 3) Set title to "A vs B".
# Stretch: Add `alpha=0.6` and compare readability.
### Your code starts here.
### Your code ends here.
5.2.2.4. Bar Plots#
Bar plots are one of the most common ways to compare categorical data visually. They represent quantities as rectangular bars whose length (or height) corresponds to the value being measured.
Both bar() and barh() create bar charts — the difference is simply orientation. Stacked bar charts, on the other hand, show how multiple subcategories contribute to a total within each main category.
Plot Type |
Orientation |
Purpose |
Best For |
|---|---|---|---|
Bar Plot |
Vertical |
Compare category values |
Simple category comparisons |
Barh Plot |
Horizontal |
Compare category values with long labels |
Readability and ranking-type data |
Stacked Bar |
Either |
Show part-to-whole relationships |
Composition of totals across categories |
Use it when you compare one number across categories, or show how a total splits into parts (stacked).
Avoid it when the x-axis is time with many points (use a line) or the value axis does not start at zero; section 5.3 shows why.
5.2.2.4.1. Vertical Bar Plot#
### total revenue for each category, in thousands of dollars
cat_rev = sales.groupby("category")["revenue"].sum() / 1000
print(cat_rev.round(1), "\n")
cat_rev.plot(kind="bar",
figsize=(4, 3), edgecolor="white", alpha=0.9, fontsize=8, rot=0,
xlabel="", ylabel="Revenue ($K)", title="Revenue by Category, 2024-2025");
category
Apparel 2620.5
Electronics 3801.8
Home 2497.9
Name: revenue, dtype: float64
5.2.2.4.2. Horizontal Bar Plot#
### bar plot horizontal: total units sold in each region
sales.groupby("region")["units"].sum().plot(kind="barh",
figsize=(4, 3), edgecolor="white", alpha=0.9, fontsize=8,
xlabel="Units sold", ylabel="", title="Units Sold by Region, 2024-2025");
5.2.2.4.3. Stacked Bar Plot#
### part of a whole: how each region's revenue splits across categories
region_cat = sales.groupby(["region", "category"])["revenue"].sum() / 1000
print(region_cat.round(1), "\n")
print(region_cat.unstack().round(1))
region_cat.unstack().plot(kind="bar",
stacked=True, rot=0,
figsize=(4, 3), edgecolor="white", alpha=0.9, fontsize=8,
xlabel="", ylabel="Revenue ($K)", title="Revenue by Region and Category")
plt.legend(title="Category", bbox_to_anchor=(1.02, 1), loc="upper left", fontsize=7)
plt.tight_layout()
region category
East Apparel 570.6
Electronics 837.4
Home 536.9
North Apparel 640.8
Electronics 919.6
Home 612.8
South Apparel 746.5
Electronics 1073.2
Home 709.0
West Apparel 662.6
Electronics 971.7
Home 639.3
Name: revenue, dtype: float64
category Apparel Electronics Home
region
East 570.6 837.4 536.9
North 640.8 919.6 612.8
South 746.5 1073.2 709.0
West 662.6 971.7 639.3
Each bar is one region’s total revenue, and the colored pieces show how much of it comes from each category. In every region Electronics is the largest piece.
5.2.2.5. BoxPlots#
Use it when you compare the spread of a number across a few groups and want to spot outliers.
Avoid it when the shape matters, such as two peaks, because a box hides it; use a histogram or KDE.
tips.boxplot(
column="tip",
by="sex",
figsize=(4, 3),
fontsize=8
)
plt.suptitle("") # removes default "Boxplot grouped by sex" title
plt.title("Tip Distribution by Gender")
plt.xlabel("")
plt.ylabel("Tip ($)")
plt.grid(alpha=0.25)
plt.tight_layout()
How to read each box:
The green line inside the box is the median tip: the middle value.
The bottom of the box is the 25th percentile: about 25% of tips are below this.
The top of the box is the 75th percentile: about 75% of tips are below this.
The box shows the middle 50% of tips.
The whiskers show the usual range of non-outlier values.
The circles are outliers: unusually high tip amounts.
### Exercise: Box Plot Comparison
# Goal: Compare spread and outliers across `df2` columns.
# Requirements:
# 1) Create a box plot for all numeric columns in `df2`.
# 2) Use `figsize=(8, 4)`.
# 3) Set title to "Box Plot of df2".
# Stretch: Rotate x tick labels by 30 degrees for readability.
### Your code starts here.
### Your code ends here.
5.2.2.6. Area Plot#
Use it when you show how a total and its parts change over time.
Avoid it when there are many series: each layer sits on the ones below, so the upper layers are hard to read.
flights = sns.load_dataset("flights")
df = flights.pivot(index="year", columns="month", values="passengers")
df.plot(
kind="area",
figsize=(5, 3),
alpha=0.5,
fontsize=8,
title="Passengers by Month"
)
plt.xlabel("Year")
plt.ylabel("Passengers")
plt.legend(title="Month", bbox_to_anchor=(1.05, 1), loc="upper left", fontsize=6)
plt.tight_layout()
5.2.2.7. KDE Plot#
A Kernel Density Estimate (KDE) plot is smooth version of histogram.
Density tells you where values are concentrated. A higher curve means more values are packed in that region. The exact y-value doesn’t matter — the shape and peaks are what you read.
The peak shows where most values are concentrated
A wider curve means more spread in the data
The area under the curve always equals 1.0
The y-axis shows density — not count or percentage
Use it when you want the smooth shape of a distribution, or to overlay a few distributions on one chart.
Avoid it when the sample is small: the smooth curve can suggest values that never occur, such as negative amounts.
# %pip install scipy ### ensure scipy is installed; uncomment when done
# penguins — body mass or flipper length, clear multi-modal distribution
penguins = sns.load_dataset("penguins").drop(columns=\
["bill_length_mm", "bill_depth_mm", "flipper_length_mm"])
print(penguins.head())
penguins["body_mass_g"].plot(
kind="kde",
title="Penguin Body Mass",
figsize=(4,2.5)
);
species island body_mass_g sex
0 Adelie Torgersen 3750.0 Male
1 Adelie Torgersen 3800.0 Female
2 Adelie Torgersen 3250.0 Female
3 Adelie Torgersen NaN NaN
4 Adelie Torgersen 3450.0 Female
You can also overlay KDE with histogram, which makes it clear that a KDE is a smoothed out version of histogram.
penguins = sns.load_dataset("penguins").drop(columns=\
["bill_length_mm", "bill_depth_mm", "flipper_length_mm"])
penguins["body_mass_g"].plot(
kind="hist", bins=20,
edgecolor="white", alpha=0.5,
density=True, ### must be density=True to overlay KDE on histogram
# title="Histogram",
fontsize=8,
label="Histogram",
figsize=(4, 2.5)
)
penguins["body_mass_g"].plot(
kind="kde",
# title="KDE",
fontsize=8,
label="KDE"
)
plt.legend()
plt.tight_layout()
### Exercise: KDE for a Single Variable
# Goal: Plot a smooth estimate of one distribution.
# load dataset if needed tips = sns.load_dataset("tips")
# Requirements:
# 1) Plot KDE for `tips['tip']`.
# 2) Set `figsize=(4, 3)`.
# 3) Add title "KDE of Column tip".
### Your code starts here.
### Your code ends here.
### Exercise: Multi-Column Density Plot
# Goal: Compare distributions of all `df2` columns on one chart.
# Requirements:
# 1) Create a density plot for `df2`.
# 2) Set `figsize=(8, 4)`.
# 3) Add title "Density Curves for df2".
# Stretch: Keep only two columns and compare how interpretation changes.
### Your code starts here.
### Your code ends here.
5.2.2.8. Hexagonal Bin Plot#
Hexagonal bin plots are useful for bivariate Data and is an alternative to scatterplot.
Use it when a scatter plot has so many points that they pile up into a blob.
Avoid it when there are only a few dozen points; a scatter plot shows each one.
np.random.seed(42)
df = pd.DataFrame(np.random.randn(1000, 2), columns=['a', 'b'])
df.plot.hexbin(x='a', y='b',
gridsize=25,
cmap='Oranges',
figsize=(5, 4),
);
### Exercise: Hexbin for Dense Data
# Goal: Visualize dense bivariate data without overplotting.
# Requirements:
# 1) Use the existing `df` with columns `a` and `b`.
# 2) Create a hexbin plot with `gridsize=25`.
# 3) Use a visible colormap (for example, `cmap='Oranges'`).
# Stretch: Change `gridsize` to 15 and 40 and compare detail vs smoothness.
### Your code starts here.
### Your code ends here.
5.2.3. Section Practice#
Use this short exercise to check the main workflow from this section.
### Exercise: Three Questions, Three Charts
# Three managers send questions about the `sales` data. For each one, name the
# question type, summarize the data, and draw the chart that fits.
# 1) "Which region spent the most on ads over the two years?"
# (total `ad_spend` by region)
# 2) "What does a region's daily ad spend usually look like?"
# (add up `ad_spend` for each date and region, then look at its spread)
# 3) "On days when a region spends more on ads, does it sell more units?"
# (use the date-and-region totals from step 2, with `units` too)
# Print exactly:
# 1: comparison
# 2: distribution
# 3: relationship
### Your code starts here.
### Your code ends here.
1: comparison
2: distribution
3: relationship