SyntaxPilot
Courses/Data Analytics with Python/Lesson 31
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

Data Analytics with Python · Lesson 31 of 90

Charts 2: histograms, scatter, box plots and subplots

plt.subplotsmultiple axeshistogrambinsscatter plotbox plotannotatetextcolours and colormapsstylestick formattingtwin axes (dual axis)DataFrame.plot

These are the notes for Data Analytics with Python, episode 31. Last episode's line and bar charts answer how much? and how did it change? Today the owner asks three new kinds of question, and each one needs a new chart: what does a typical bill look like? (a histogram), does waiting longer hurt the rating? (a scatter plot), and which stall's bills are the most unpredictable? (a box plot). Then you put many charts in one image with plt.subplots, point at the story with annotate and text, clean up tick labels, add a second y axis with twinx, change the look with styles, and use the pandas shortcut DataFrame.plot. Every term is defined the first time it appears and collected in the Glossary.

Every program below was run for real (Python 3.13, NumPy 2.5.3, pandas 3.0.5, matplotlib 3.11.2, on a server with no screen, so charts are saved with savefig); the images are the files those exact programs saved. The bills, waits and ratings are made-up data generated with a fixed seed.

The data: random but repeatable

import sys; sys.tracebacklimit = 0
import numpy as np
import matplotlib.pyplot as plt
rng = np.random.default_rng(31)
bills = rng.gamma(4, 30, 500).round()   # 500 Pune bills, rupees
  • sys.tracebacklimit = 0 makes Python print only the last line of an error, so error messages stay short.
  • np.random.default_rng(31) (episode 10) makes a random number generator with seed 31: the same "random" numbers every run, so you get exactly the outputs shown here.
  • rng.gamma(4, 30, 500) draws 500 numbers from a gamma distribution, a shape that is always positive, bunched on the left with a long tail to the right. It is a realistic shape for bills: most are around 100 rupees, a few are big. You don't need to know the maths; it just makes believable data.

Histogram: what does a typical bill look like?

The obvious attempt: we know bar charts, so draw one bar per bill.

fig, ax = plt.subplots()
ax.bar(range(500), bills)
ax.set_title("500 bills, one bar each")
fig.savefig("bars500.png")
print(len(bills), "bills, average", bills.mean().round(1))
500 bills, average 125.1

bars500.png

A barcode. The bars follow the random order the bills arrived in; no shape, no answer.

Why it fails: the question is not about any single bill. It is about how many bills fall in each range. A cashier would sort the bills into trays (under 50, 50 to 100, 100 to 150 ...) and count each tray.

The fix: a histogram. A histogram counts how many values fall in each range and draws the counts as touching bars. Each range is a bin; the boundaries between bins are the bin edges.

fig, ax = plt.subplots()
counts, edges, _ = ax.hist(bills, bins=10, edgecolor="white")
ax.set(title="Pune bills", xlabel="Bill (rupees)", ylabel="Number of bills")
fig.savefig("hist10.png")
print(counts.astype(int))
print(edges.round())
[ 43  96  92 100  77  45  29   7   6   5]
[ 15.  48.  81. 114. 147. 180. 213. 246. 279. 312. 345.]

hist10.png

  • ax.hist(values, bins=10) splits the range from the smallest to the largest value (15 to 345) into 10 equal-width bins (33 rupees each), counts the values in each, and draws the bars.
  • It returns three things: the counts (43 bills between 15 and 48, then 96, 92, 100 ...), the edges (11 edges for 10 bins), and the bar objects (we ignore them with _).
  • edgecolor="white" draws a thin line between bars so you can see each bin.
  • ax.set(title=..., xlabel=..., ylabel=...) sets several properties in one call.

Reading it. Most bills are between about 50 and 150 rupees, and a long tail stretches to the right: a few big group orders. A distribution with a long tail on the right is right-skewed (positively skewed). The distribution of a variable is which values occur and how often; a histogram is a picture of it.

Histogram vs bar chart. In a bar chart each bar is a separate category (Pune, Nashik), so bars have gaps and their order can change. In a histogram the x axis is one continuous number line cut into ranges, so the bars touch and their order is fixed.

Choosing the number of bins

for b in [4, 150]:
    fig, ax = plt.subplots()
    ax.hist(bills, bins=b, edgecolor="white")
    ax.set_title(f"bins={b}")
    fig.savefig(f"bins{b}.png")
print("saved bins4.png and bins150.png")
saved bins4.png and bins150.png
bins=4 bins=150
bins4.png bins150.png
  • Too few bins (4) hide the shape: the long tail is swallowed into one block.
  • Too many bins (150) show noise: each bin holds only a few bills, so random luck makes the bars jump.
  • Start with 10 to 30 bins, try a few, and keep the one where the shape is clear and stable. bins can also be a list of edges, e.g. bins=[0, 50, 100, 150, 200, 400], or a rule such as bins="auto".

Scatter plot: does waiting longer hurt the rating?

import sys; sys.tracebacklimit = 0
import numpy as np
import matplotlib.pyplot as plt
rng = np.random.default_rng(31)
wait = rng.uniform(1, 15, 200).round(1)            # minutes
rating = (5 - 0.18 * wait + rng.normal(0, 0.4, 200)).clip(1, 5).round(1)
bill = rng.gamma(4, 30, 200).round()
  • rng.uniform(1, 15, 200): 200 waits spread evenly between 1 and 15 minutes.
  • The rating starts at 5, drops 0.18 per minute of waiting, plus random noise (rng.normal(0, 0.4, 200): small random ups and downs). .clip(1, 5) keeps every value between 1 and 5.

The obvious attempt: a line chart takes x and y, so plot wait against rating.

fig, ax = plt.subplots()
ax.plot(wait, rating)
ax.set(title="Wait vs rating", xlabel="Wait (min)", ylabel="Rating")
fig.savefig("wait_line.png")
print("saved wait_line.png")
saved wait_line.png

wait_line.png

Why it fails: plot joins the points in list order. The orders are in random order, so the line zigzags back and forth: a scribble.

The fix: a scatter plot. A scatter plot draws one dot per row at its (x, y) position and joins nothing. It shows the relationship between two numeric variables: do they move together?

fig, ax = plt.subplots()
sc = ax.scatter(wait, rating, c=bill, cmap="viridis", alpha=0.8)
fig.colorbar(sc, label="Bill (rupees)")
ax.set(title="Longer wait, lower rating", xlabel="Wait (min)", ylabel="Rating")
fig.savefig("scatter.png")
print(len(wait), "orders, ratings from", rating.min(), "to", rating.max())
200 orders, ratings from 1.5 to 5.0

scatter.png

  • The dots slope down: longer waits go with lower ratings. (Measuring how strong such a relationship is, correlation, comes in the statistics episodes.)
  • c=bill colours each dot by a third number. cmap="viridis" picks the colormap: a rule that turns a number into a colour (viridis runs from dark purple for small values through green to yellow for large ones). Viridis changes smoothly from dark to light, so it stays readable for most colour-blind viewers and in black-and-white print.
  • fig.colorbar(sc, label=...) adds the colorbar, the key showing which colour means which value. ax.scatter returns the dots (sc) so the colorbar knows their colours.
  • alpha=0.8: slightly see-through dots, so overlapping dots still show.
  • Here the yellow (big) and purple (small) bills are mixed everywhere: the bill size does not depend on the wait.
  • Other useful arguments: s= dot size, marker=, color= one fixed colour.

Colours

  • Named colours: "red", "gray", "lightgray"; the default palette: "tab:blue", "tab:orange", "tab:green", "tab:red" ...
  • Hex codes: "#f57c20" (red, green, blue as two hex digits each).
  • Sequential colormaps ("viridis", "Blues", "YlOrBr") for numbers from low to high; diverging ones ("RdBu") for values above and below a middle point; qualitative ones ("tab10") for categories.

Box plot: which stall is most unpredictable?

import sys; sys.tracebacklimit = 0
import numpy as np
import matplotlib.pyplot as plt
rng = np.random.default_rng(31)
pune = rng.gamma(4, 30, 300).round()
nashik = rng.gamma(9, 11, 300).round()
mumbai = rng.gamma(2.5, 60, 300).round()

The obvious attempt: three histograms on the same axes.

fig, ax = plt.subplots()
for name, b in [("Pune", pune), ("Nashik", nashik), ("Mumbai", mumbai)]:
    ax.hist(b, bins=30, alpha=0.5, label=name)
ax.legend()
fig.savefig("overlap.png")
print("saved overlap.png")
saved overlap.png

overlap.png

Why it fails: the colours mix into mud where they overlap. Fine for two groups, hopeless for three, impossible for ten.

The fix: a box plot, which summarises each group with five numbers. Picture a class lined up from shortest to tallest:

  • Median: the student exactly in the middle (half shorter, half taller). The line inside the box.
  • First quartile (Q1): the value one quarter of the way along (25% of values are below it). Third quartile (Q3): three quarters along (75% below). The box goes from Q1 to Q3 and holds the middle half of the values.
  • Interquartile range (IQR) = Q3 − Q1, the box height (episode 23).
  • Whiskers: lines from the box to the furthest values still within 1.5 × IQR of the box.
  • Outliers (fliers): values beyond the whiskers, drawn as separate dots, like the basketball player in the class line.
  • A percentile is the value below which that percent of the data lies: the 25th percentile is Q1, the 50th is the median, the 75th is Q3.
fig, ax = plt.subplots()
ax.boxplot([pune, nashik, mumbai], tick_labels=["Pune", "Nashik", "Mumbai"])
ax.set(title="Bills by stall", ylabel="Bill (rupees)")
fig.savefig("box.png")
for name, b in [("Pune", pune), ("Nashik", nashik), ("Mumbai", mumbai)]:
    q1, med, q3 = np.percentile(b, [25, 50, 75])
    print(f"{name:7} Q1={q1:5.0f} median={med:5.0f} Q3={q3:5.0f}")
Pune    Q1=   79 median=  118 Q3=  165
Nashik  Q1=   74 median=   98 Q3=  122
Mumbai  Q1=   75 median=  132 Q3=  203

box.png

  • ax.boxplot(list_of_groups, tick_labels=[...]) draws one box per group. (Older tutorials write labels=; it was renamed in matplotlib 3.9, and in 3.11 the old name raises TypeError: Axes.boxplot() got an unexpected keyword argument 'labels'.)
  • Nashik: the smallest, tightest box (74 to 122): predictable bills.
  • Mumbai: the highest median (132), by far the tallest box (75 to 203) and longest whiskers, plus outliers above 400: the most unpredictable.
  • f"{name:7}" pads the name to 7 characters and {q1:5.0f} prints a number 5 wide with no decimals, so the columns line up.

Subplots: many charts in one figure

import sys; sys.tracebacklimit = 0
import matplotlib.pyplot as plt
months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"]
pune = [7900, 8800, 9400, 10100, 11800, 9900]
revenue = [134300, 149600, 159800, 191900, 224200, 188100]   # price up in April

(Revenue = cups × 17 rupees, and × 19 from April when the price went up.)

The obvious attempt: ask for a 2 × 2 grid and plot as usual.

fig, ax = plt.subplots(2, 2)
ax.plot(months, pune)
AttributeError: 'numpy.ndarray' object has no attribute 'plot'

Why: plt.subplots(rows, cols) with more than one chart returns a NumPy array of Axes, not one Axes. An array can't plot.

The fix: call it axs and pick each Axes by [row, col], like a seat in a cinema.

fig, axs = plt.subplots(2, 2, figsize=(10, 7))
print(type(axs).__name__, axs.shape)
axs[0, 0].plot(months, pune, marker="o")
axs[0, 0].set_title("Cups per month")
axs[0, 1].bar(months, revenue, color="tab:green")
axs[0, 1].set_title("Revenue per month")
axs[1, 0].barh(months, pune, color="tab:orange")
axs[1, 1].plot(months, revenue, color="tab:red")
fig.suptitle("Pune stall, Jan-Jun")
fig.tight_layout()
fig.savefig("grid.png")
ndarray (2, 2)

grid.png

  • axs[0, 0] is top-left, axs[0, 1] top-right, axs[1, 0] bottom-left, axs[1, 1] bottom-right.
  • With one row or one column the array is 1-D: plt.subplots(1, 3) → axs[0], axs[1], axs[2]. axs.flat walks through any grid in order.
  • fig.suptitle: one title over the whole figure ("super title").
  • fig.tight_layout(): moves the axes apart so titles and labels don't overlap.
  • sharex=True / sharey=True make all subplots use the same x / y scale (used in episode 32).

Annotations, text and tick formatting

from matplotlib.ticker import StrMethodFormatter
fig, ax = plt.subplots(figsize=(8, 4.5))
ax.plot(months, pune, marker="o")
ax.annotate("May peak: 11,800", xy=(4, 11800), xytext=(1, 11300),
            arrowprops=dict(arrowstyle="->"))
ax.text(3.1, 8100, "rains start in June", color="gray")
ax.yaxis.set_major_formatter(StrMethodFormatter("{x:,.0f}"))
fig.savefig("annotate.png")
print("saved annotate.png")
saved annotate.png

annotate.png

  • ax.annotate(text, xy=..., xytext=..., arrowprops=...): writes a note at xytext and draws an arrow to the point xy. With text categories on the x axis, the positions are 0, 1, 2 ... so May is x = 4.
  • ax.text(x, y, text): plain text at a position, no arrow.
  • A tick is a marked position on an axis with a label. A tick formatter controls how tick labels look. StrMethodFormatter("{x:,.0f}") uses Python's format codes: , adds thousands separators, .0f means no decimals, so 11500 becomes 11,500.
  • Other tick tools: ax.set_xticks(positions, labels=...), ax.tick_params(rotation=45), PercentFormatter for percentages.

Twin axes: two units on one chart

The obvious attempt: cups and revenue on the same axes.

fig, ax = plt.subplots()
ax.plot(months, pune, label="Cups")
ax.plot(months, revenue, label="Revenue")
ax.legend()
fig.savefig("same_axis.png")
print("saved same_axis.png")
saved same_axis.png

Why it fails: revenue is in hundreds of thousands, cups in thousands, and they share one y axis, so the cups line is squashed flat at the bottom.

The fix: twin axes. ax.twinx() makes a second Axes that shares the x axis and has its own y axis on the right. A chart with two y axes is a dual-axis chart.

fig, ax = plt.subplots(figsize=(8, 4.5))
ax.plot(months, pune, color="tab:blue", marker="o")
ax.set_ylabel("Cups sold", color="tab:blue")
ax2 = ax.twinx()
ax2.plot(months, revenue, color="tab:red", marker="s")
ax2.set_ylabel("Revenue (rupees)", color="tab:red")
fig.savefig("twin.png", bbox_inches="tight")
print(type(ax2).__name__)
Axes
One axis Twin axes
same_axis.png twin.png

From April, revenue (red) climbs faster than cups (blue): the price rise worked. Colour each y label like its line so readers know which scale is which.

Warning: each y axis can be stretched independently, so where the two lines sit or cross means nothing, and dual-axis charts are easy to abuse. Episode 32 shows the same data telling two opposite stories. Often two stacked subplots with sharex=True are clearer.

Styles

print(len(plt.style.available), "styles, e.g.", plt.style.available[:4])
plt.style.use("ggplot")
fig, ax = plt.subplots()
ax.plot(months, pune, marker="o")
ax.set_title("ggplot style")
fig.savefig("ggplot.png")
28 styles, e.g. ['Solarize_Light2', 'bmh', 'classic', 'dark_background']

ggplot.png

  • A style (style sheet) is a saved set of settings (colours, fonts, background, grid) applied to every chart after it.
  • plt.style.use("ggplot") imitates ggplot2, a popular plotting library for the R language: grey background, white grid. Others: "seaborn-v0_8-whitegrid", "fivethirtyeight", "tableau-colorblind10", "default" to go back.
  • Temporary style for one block: with plt.style.context("bmh"): ....

DataFrame.plot: the pandas shortcut

import pandas as pd
nashik = [5200, 5600, 6100, 6000, 6900, 6400]
df = pd.DataFrame({"Pune": pune, "Nashik": nashik}, index=months)
ax = df.plot(kind="bar", title="Cups per month", rot=0)
ax.set_ylabel("Cups sold")
ax.figure.savefig("dfbar.png")
print(type(ax).__name__)
Axes

dfbar.png

  • df.plot(kind=...) calls matplotlib for you: the index goes on the x axis, each column becomes a series with its own colour, and the legend comes from the column names.
  • kind can be "line" (default), "bar", "barh", "hist", "box", "scatter" (with x= and y=), "area", "pie". rot=0 keeps tick labels upright.
  • It returns a normal Axes, so you can keep customising; ax.figure is its Figure. Pass ax=axs[0, 1] to draw into a subplot.

Mini project: a one-row dashboard

import sys; sys.tracebacklimit = 0
import numpy as np
import matplotlib.pyplot as plt
rng = np.random.default_rng(31)
bills = rng.gamma(4, 30, 500).round()
wait = rng.uniform(1, 15, 500).round(1)
rating = (5 - 0.18 * wait + rng.normal(0, 0.4, 500)).clip(1, 5)
fig, axs = plt.subplots(1, 3, figsize=(15, 4.5))
axs[0].hist(bills, bins=20, edgecolor="white")
axs[0].set(title="How big are bills?", xlabel="Bill (rupees)")
axs[1].scatter(wait, rating, alpha=0.4, s=12)
axs[1].set(title="Wait vs rating", xlabel="Wait (min)")
axs[2].boxplot([bills[wait < 8], bills[wait >= 8]], tick_labels=["fast", "slow"])
axs[2].set(title="Bills: fast vs slow service")
fig.tight_layout()
fig.savefig("dashboard.png", dpi=150)
print("saved dashboard.png")
saved dashboard.png

dashboard.png

A dashboard is a set of charts that answer related questions at a glance. Here: a distribution (histogram), a relationship (scatter) and a comparison (box plot, using boolean masks from episode 9: bills[wait < 8] keeps the bills of orders served in under 8 minutes). Fast and slow service have similar bills, so slow service isn't explained by big orders.

Common mistakes

Code / habit Real error / symptom Why Fix
fig, ax = plt.subplots(2, 2) then ax.plot(...) AttributeError: 'numpy.ndarray' object has no attribute 'plot' many axes come back as an array axs[0, 0].plot(...)
ax.plot(wait, rating) for unordered data no error; a scribble plot joins points in list order ax.scatter(wait, rating)
bins=4 or bins=150 no error; hidden or noisy shape too few / too many bins try 10-30 bins, compare
one bar per value (ax.bar(range(500), bills)) no error; a barcode the question is about ranges ax.hist(bills)
overlapping histograms for 3+ groups no error; mud colours mix box plot (or small multiples)
cups and revenue on one axis no error; one line squashed flat very different scales ax.twinx() or two subplots
subplot labels overlapping text on top of text default spacing fig.tight_layout()
ax.boxplot(data, labels=["Pune"]) (old tutorials) TypeError: Axes.boxplot() got an unexpected keyword argument 'labels'. Did you mean 'label'? (matplotlib 3.11) renamed in 3.9, old name removed tick_labels=

Practice

1. Make 1,000 random heights (rng.normal(165, 9, 1000), in cm) and draw three histograms side by side with 5, 20 and 200 bins. Which one shows the shape best?

Solution
import sys; sys.tracebacklimit = 0
import numpy as np
import matplotlib.pyplot as plt
rng = np.random.default_rng(1)
heights = rng.normal(165, 9, 1000).round(1)       # cm
fig, axs = plt.subplots(1, 3, figsize=(15, 4), sharey=False)
for ax, b in zip(axs, [5, 20, 200]):
    ax.hist(heights, bins=b, edgecolor="white")
    ax.set(title=f"bins={b}", xlabel="Height (cm)")
fig.tight_layout()
fig.savefig("p1.png")
print(heights.min(), heights.max())
133.1 198.8

20 bins shows the bell shape clearly; 5 bins is too coarse and 200 bins is spiky noise. zip(axs, [5, 20, 200]) pairs each Axes with its bin count.

2. Scatter of daily study hours against marks for 80 students, coloured by attendance, with a colorbar.

Solution
hours = rng.uniform(0, 6, 80).round(1)
attendance = rng.uniform(50, 100, 80).round()
marks = (35 + 8 * hours + 0.2 * attendance + rng.normal(0, 6, 80)).clip(0, 100).round()
fig, ax = plt.subplots()
sc = ax.scatter(hours, marks, c=attendance, cmap="viridis")
fig.colorbar(sc, label="Attendance (%)")
ax.set(title="Study hours vs marks", xlabel="Hours per day", ylabel="Marks")
fig.savefig("p2.png")
print(len(hours), "students")
80 students

3. Turn the 2 × 2 grid from the notes into a dashboard with one annotation: an arrow pointing at the highest revenue month.

Solution

Add to the grid program, before fig.savefig:

axs[1, 1].annotate("May: 2,24,200", xy=(4, 224200), xytext=(0.5, 210000),
                   arrowprops=dict(arrowstyle="->"))

Each Axes has its own annotate; xy=(4, 224200) is May (position 4) at its revenue.

4. What do fig, axs = plt.subplots(1, 2) then print(axs.shape, type(axs[0]).__name__) print?

Solution
fig, axs = plt.subplots(1, 2)
print(axs.shape, type(axs[0]).__name__)
(2,) Axes

One row gives a 1-D array of 2 Axes, so you index with a single number.

5. For the values [1, 2, 3, 4, 5, 6, 7, 8, 40], work out Q1, the median, Q3, the IQR and the upper whisker limit. Is 40 an outlier?

Solution
import numpy as np
q1, med, q3 = np.percentile([1, 2, 3, 4, 5, 6, 7, 8, 40], [25, 50, 75])
print(q1, med, q3, "IQR", q3 - q1, "upper fence", q3 + 1.5 * (q3 - q1))
3.0 5.0 7.0 IQR 4.0 upper fence 13.0

40 is above 13, so the box plot draws it as an outlier dot; the upper whisker stops at 8, the largest value within the fence.

Quick quiz

fig, axs = plt.subplots(3, 2)
print(axs.shape)

What does it print? A. (2, 3) B. (3, 2) C. (6,) D. AttributeError

Answer

B. (3, 2). plt.subplots(rows, cols) returns an array of Axes shaped (rows, cols). axs[2, 1] is the bottom-right chart.

Interview questions

  1. Histogram vs bar chart? A histogram shows the distribution of one numeric variable with touching bins on a continuous axis; a bar chart compares separate categories.
  2. How does the number of bins affect a histogram? Too few hide the shape, too many show noise; try several and pick the stable one.
  3. When do you use a scatter plot? To show the relationship between two numeric variables; colour or size can add a third.
  4. What does a box plot show? The median, Q1 and Q3 (the box, whose height is the IQR), whiskers to the furthest points within 1.5 × IQR, and outliers as dots.
  5. What does plt.subplots(2, 2) return? A Figure and a 2 × 2 NumPy array of Axes.
  6. Why tight_layout()? To stop titles and labels of neighbouring subplots overlapping.
  7. What is twinx and what's the risk? A second Axes sharing x with its own y axis; because both scales are free, dual-axis charts can suggest false relationships.
  8. What is a colormap? A mapping from numbers to colours; use sequential maps for low-to-high values, diverging for values around a midpoint, qualitative for categories.
  9. How do you format tick labels with thousands separators? ax.yaxis.set_major_formatter(StrMethodFormatter("{x:,.0f}")).
  10. What does df.plot() return? A matplotlib Axes, so you can keep customising it.

Glossary

Term Meaning Example
Random number generator (rng) Object that produces random numbers np.random.default_rng(31)
Seed Starting number that makes random numbers repeatable 31
Gamma distribution A positive, right-tailed shape used here for realistic bills rng.gamma(4, 30, 500)
Noise Random ups and downs around the real pattern rng.normal(0, 0.4, 200)
clip Limits values to a range .clip(1, 5)
Distribution Which values occur and how often most bills 50-150 rupees
Histogram Counts of values per range, drawn as touching bars ax.hist(bills, bins=10)
Bin One range in a histogram 48 to 81 rupees
Bin edges The boundaries between bins [15, 48, 81, ...]
Tail The thin far end of a distribution a few big bills
Right-skewed Long tail on the right bills
Scatter plot One dot per row at (x, y), nothing joined ax.scatter(wait, rating)
Relationship How two variables move together longer wait, lower rating
c= Colour each dot by a value c=bill
Colormap (cmap) Rule turning numbers into colours "viridis"
Colorbar Key showing which colour means which value fig.colorbar(sc)
Hex colour code A colour written as #RRGGBB "#f57c20"
Box plot Five-number summary of a group, drawn as a box ax.boxplot([...])
Median The middle value when sorted 118 rupees
Quartile (Q1, Q3) Values with 25% / 75% of the data below them Q1 = 79
Percentile Value below which that % of the data lies 75th percentile = Q3
Interquartile range (IQR) Q3 − Q1, the box height 165 − 79 = 86
Whiskers Lines to the furthest values within 1.5 × IQR box plot
Outlier A value far from the rest (beyond the whiskers) a 500-rupee bill
plt.subplots(r, c) A figure with a grid of axes plt.subplots(2, 2)
axs[row, col] One Axes in the grid axs[0, 1]
suptitle Title over the whole figure fig.suptitle(...)
tight_layout Spaces subplots so nothing overlaps fig.tight_layout()
sharex / sharey All subplots use the same x / y scale sharey=True
annotate Note with an arrow to a point ax.annotate("May peak", xy=(4, 11800), ...)
text Plain text at a position ax.text(3.1, 8100, "...")
Tick A marked position on an axis with a label 11,500
Tick formatter Controls how tick labels look StrMethodFormatter("{x:,.0f}")
Twin axes (twinx) Second Axes sharing x, own y on the right ax2 = ax.twinx()
Dual-axis chart A chart with two y axes cups and revenue
Style Saved set of look settings plt.style.use("ggplot")
DataFrame.plot pandas method that draws with matplotlib df.plot(kind="bar")
Dashboard Several charts answering related questions together the 1 × 3 mini project
Boolean mask True/False array used to pick values bills[wait < 8]

Summary

  • Distribution → histogram (ax.hist); the number of bins changes what you see: try several.
  • Relationship → scatter plot (ax.scatter), with c= + colormap + colorbar for a third number.
  • Comparing groups → box plot (ax.boxplot): median, Q1-Q3 box (IQR), whiskers, outliers.
  • plt.subplots(r, c) returns an array of Axes: axs[row, col]; finish with suptitle and tight_layout.
  • annotate and text point at the story; tick formatters clean up labels.
  • twinx adds a second y axis for a different unit, but dual axes can mislead.
  • plt.style.use changes the look; df.plot(kind=...) is the pandas shortcut and returns an Axes.
  • Next episode: choosing the right chart, and how charts mislead.