5.2. Pandas Chart Types#

Hide code cell source

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

np.random.seed(42)
df1 = pd.DataFrame({
    'A': np.arange(100),
    'B': np.random.randn(100).cumsum(),
    'C': np.random.randn(100).cumsum(),
})
df2 = pd.DataFrame({
    'a': np.random.rand(50),
    'b': np.random.rand(50),
    'c': np.random.rand(50),
})
df = pd.DataFrame(np.random.randn(1000, 2), columns=['a', 'b'])
tips = sns.load_dataset('tips')

path_data = '../../data/'
sales = pd.read_csv(path_data + 'retail_daily_sales.csv')
sales['month'] = sales['date'].str[:7]

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()
../../_images/af573a8c7b5c54921f824c099f26cc2170e0dbba405fca00803ca699eb45fc13.png

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()
../../_images/0f0260952af22f25bb32a4f61caaa09679d9b863491ad95462179c90c8075734.png

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
../../_images/52aa19745bbe1037036b6ad3126cd76cef7681763d76fa340261e0be687a8e07.png

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()
../../_images/db8ab671ed652b12191d0a09790955e3e363c4e755c34546b9265da6147baa17.png

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()
../../_images/4a52af36761247ece4cd6d084cdd56d54f968be64d4ef39af4e03070fbf3b566.png
### 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.

Hide code cell source

### Solution
### Question type: trend (a number changing over time), so use a line chart.
print("Question type: trend")
monthly_units = sales.groupby("month")["units"].sum()

monthly_units.plot.line(figsize=(5, 2.5), fontsize=8, marker="o", markersize=3,
                        title="Monthly Units Sold")
plt.xlabel("Month")
plt.ylabel("Units")
plt.tight_layout()
Question type: trend
../../_images/61223d04c063907d81845dde28c9da3c9333db83ca92dbc1becbaa5618b6411b.png

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()
../../_images/0f02c3359b9a56077f353ba2c70bf9ea82facae550c908c70d9b86e3c7c4fb5e.png

.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.

Hide code cell source

### Solution
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

try:
    df1
except NameError:
    rng = np.random.default_rng(0)
    df1 = pd.DataFrame(rng.normal(size=(100, 3)), columns=['A', 'B', 'C'])

ax = df1['B'].plot(kind='line', figsize=(8, 4), lw=2, label='B')
df1['B'].rolling(window=10).mean().plot(ax=ax, label='Rolling mean')
ax.set_xlabel('Index')
ax.set_ylabel('B values')
ax.legend()
plt.show()
../../_images/7df930200c4e0a3fe0a7a5040cea501aee09a64d1edcfc37abdb2e1dfe08b788.png

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()
../../_images/d7d43e42aaea91fe00d74cc9a17d98362dd78ffb927919079d8fac990b8d09d3.png
### 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.

Hide code cell source

### Solution
ax = sales['revenue'].plot(kind='hist', bins=50, figsize=(8, 4), alpha=0.7)
ax.axvline(sales['revenue'].mean(), linestyle='--', color='red', label='Mean')
ax.axvline(sales['revenue'].median(), linestyle='--', color='black', label='Median')
ax.set_title('Distribution of Revenue per Row')
ax.set_xlabel('Revenue ($)')
ax.legend()
plt.show()
../../_images/2bd7fde3c34f6d4424c8ff1ba2cadde1ed1c5875467e6f2608b721e0b5ab1a1d.png

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
);
../../_images/2d0b3d0ec27d64e5962f84a3526b37edc9e27bfc6075c10242008b0b2de8c1da.png
### 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.

Hide code cell source

### Solution
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

try:
    df1
except NameError:
    rng = np.random.default_rng(0)
    df1 = pd.DataFrame(rng.normal(size=(100, 3)), columns=['A', 'B', 'C'])

ax = df1.plot(kind='scatter', x='A', y='B', figsize=(7, 5), alpha=0.6)
ax.set_title('A vs B')
plt.show()
../../_images/4e87476f60a91e09235f7cfc574f80c9c83435f98c4912274647fb32e9cfe1bf.png

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 
../../_images/d9cf80d5d26c6515738c07113e56272e65c325997b3a7422c729553d89be7316.png

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");
../../_images/14d0cf618f37fe1e5e349a6c6a07d4cf28aac2eec299adad996884a52109f859.png

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
../../_images/697057dbf2211da3f06109ee7edc993b04ef70d57e5f24a7e44003ccb0b274e3.png

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()
../../_images/4fdbb133dfe08d7ac3458a8641740fede15ee9387299ff3e1e9a217aca12f03d.png

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.

Hide code cell source

### Solution
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

try:
    df2
except NameError:
    rng = np.random.default_rng(1)
    df2 = pd.DataFrame(rng.normal(size=(80, 4)), columns=['A', 'B', 'C', 'D'])

ax = df2.plot(kind='box', figsize=(8, 4))
ax.set_title('Box Plot of df2')
ax.tick_params(axis='x', rotation=30)
plt.show()
../../_images/236d6a7766ef496d167c37baf93ddc28b0629224ce688d1f66001093b9a21037.png

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()
../../_images/7064d352c1d167362c084e60cd03d25cef4f799e93e66db3c0bd017603346036.png

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
../../_images/8d6a8ed4d38193988d9903899c93ba37eae5619bea25c0c0448f3d1d093aceb8.png

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()
../../_images/5993920c3381a6e36cff5aedcf874734430edfa757adbf5f845fe3630319cb59.png
### 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.

Hide code cell source

### Solution
import seaborn as sns
import matplotlib.pyplot as plt

tips = sns.load_dataset('tips')
ax = tips['tip'].plot(kind='kde', figsize=(4, 3))
ax.set_title('KDE of Column tip')
plt.show()
../../_images/4614c68d9e64ba57b44faa80fe8542534b05efcc89acfe01be61df7d1eaf96cb.png
### 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.

Hide code cell source

### Solution
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

try:
    df2
except NameError:
    rng = np.random.default_rng(1)
    df2 = pd.DataFrame(rng.normal(size=(80, 4)), columns=['A', 'B', 'C', 'D'])

ax = df2.plot(kind='density', figsize=(8, 4))
ax.set_title('Density Curves for df2')
plt.show()
../../_images/35d5077c4f043518c60482050898200692a4beca562db6e1ff99d549278b9819.png

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),
            );
../../_images/6a4d09132fd0503c5bdb11bcd1ff8aff3ad596932aef101689397f0e1eee1c5f.png
### 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.

Hide code cell source

### Solution
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

try:
    df
except NameError:
    rng = np.random.default_rng(2)
    df = pd.DataFrame({'a': rng.normal(size=500), 'b': rng.normal(size=500)})

ax = df.plot(kind='hexbin', x='a', y='b', gridsize=25, cmap='Oranges')
ax.set_title('Hexbin Plot')
plt.show()
../../_images/1a71e98b820e6dc177f08a7056aa447ebc2d380d16df5179c7269e61ce5d25d5.png

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.

Hide code cell source

### Solution
### 1) Comparison -> bar chart, sorted so the ranking is easy to read
print("1: comparison")
(sales.groupby("region")["ad_spend"].sum().sort_values()
     .plot.barh(figsize=(4, 2.5), fontsize=8, xlabel="Ad spend ($)", ylabel="",
                title="Ad Spend by Region, 2024-2025"))
plt.tight_layout()
plt.show()

### 2) Distribution -> histogram
print("2: distribution")
region_day = sales.groupby(["date", "region"])[["ad_spend", "units"]].sum()
region_day["ad_spend"].plot.hist(bins=30, edgecolor="white", figsize=(4, 2.5), fontsize=8,
                                 title="Daily Ad Spend per Region")
plt.xlabel("Ad spend per region-day ($)")
plt.tight_layout()
plt.show()

### 3) Relationship -> scatter plot
print("3: relationship")
region_day.plot.scatter(x="ad_spend", y="units", alpha=0.3, s=8, figsize=(4, 3), fontsize=8,
                        title="Ad Spend vs. Units Sold")
plt.tight_layout()
plt.show()
1: comparison
../../_images/d34240713ededcefcfc9e33d5d2d6f5bd6383e57ce1b7dded78ad7e68fc9c2ab.png
2: distribution
../../_images/8b94fe870bce8206817257496384229a02a68dc5a0b34bd0676b9c7a409b9ed3.png
3: relationship
../../_images/a763cc642988facf597663c2f69f416380ca930722ad45380890370f04e111be.png