SyntaxPilot
Courses/Data Analytics with Python/Lesson 32
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 32 of 90

Charts 3: choosing the right chart

chart purposes (comparison, composition, distribution, relationship, trend)bar vs line vs piestacked bar100% stacked barheatmapsmall multiplesdata-ink ratiochartjunkpreattentive attributescolour for meaningaccessibility (colour-blind safe)misleading charts (truncated axis, dual-axis abuse)

These are the notes for Data Analytics with Python, episode 32. You can already draw lines, bars, histograms, scatter plots and box plots. Today's question is harder: which one should you draw? Ramesh made the owner a report with ten colourful charts, and the owner asked, "so, what should I do?" The charts were pretty and answered nothing. Here you invent the rules that fix it: the five chart purposes, bar vs line vs pie, stacked and 100% stacked bars, the heatmap, small multiples, the data-ink ratio and chartjunk, preattentive attributes, colour for meaning, colour-blind safe charts, and two ways charts mislead: the truncated axis and dual-axis abuse. Every term is defined the first time it appears and collected in the Glossary.

Every program below was run for real (Python 3.13, pandas 3.0.5, matplotlib 3.11.2, on a server with no screen); the images are the files those exact programs saved. Sales numbers are made up for teaching.

Start with the question: five chart purposes

A chart's purpose is the one question it answers. Almost every chart question is one of five kinds:

Purpose The question Example Good charts
Comparison Which is bigger? Which stall sold most? bar, horizontal bar
Composition What is the whole made of? What share of sales is chai? stacked bar, 100% stacked bar, pie (only 2-3 parts)
Distribution How are values spread? What's a typical bill? histogram, box plot (episode 31)
Relationship Do two numbers move together? Does a longer wait lower the rating? scatter plot, heatmap
Trend How does it change over time? How did cups change month by month? line, small multiples

Write the question first, name its purpose, and the chart almost picks itself.

Bar vs pie (composition)

import sys; sys.tracebacklimit = 0
import matplotlib.pyplot as plt
items = ["Masala chai", "Ginger chai", "Coffee", "Samosa",
         "Vada pav", "Poha", "Biscuits", "Lemon tea"]
sold = [1460, 1390, 1210, 1180, 1120, 980, 640, 420]

The obvious attempt: shares of a whole sound like a pie chart, a circle cut into slices whose angles are proportional to each part.

fig, ax = plt.subplots()
ax.pie(sold, labels=items)
ax.set_title("Share of items sold")
fig.savefig("pie.png")
print(f"Masala chai {sold[0]/sum(sold):.1%}, Ginger chai {sold[1]/sum(sold):.1%}")
Masala chai 17.4%, Ginger chai 16.5%

Why it fails: which is bigger, masala chai or ginger chai? Coffee or samosa? Our eyes are bad at comparing angles and areas. ({x:.1%} formats a fraction as a percentage with one decimal.)

The fix: sorted horizontal bars. All bars start from the same baseline, so you compare lengths, which the eye judges well.

fig, ax = plt.subplots(figsize=(8, 4.5))
ax.barh(items, sold, color="tab:blue")
ax.invert_yaxis()
ax.set(title="Items sold this week", xlabel="Units sold")
fig.savefig("items_barh.png", bbox_inches="tight")
print("saved items_barh.png")
saved items_barh.png
Pie Sorted bars
pie.png items_barh.png

Rule: a pie only for two or three parts that are clearly different (70% vs 30%). Otherwise, bars. Bar vs line: bars compare separate categories; lines show ordered values over time (episode 30).

Stacked and 100% stacked bars

import sys; sys.tracebacklimit = 0
import matplotlib.pyplot as plt
import pandas as pd
df = pd.DataFrame({"Chai": [5200, 2100, 6900], "Coffee": [1400, 900, 3800],
                   "Snacks": [2600, 700, 2900]}, index=["Pune", "Nashik", "Mumbai"])

A stacked bar chart puts the parts of each bar on top of each other: the bar height is the total, the segments are the parts.

ax = df.plot(kind="bar", stacked=True, rot=0, title="Sales by stall")
ax.set_ylabel("Units sold")
ax.figure.savefig("stacked.png")
print(df.sum(axis=1))
Pune       9200
Nashik     3700
Mumbai    13600
dtype: int64

stacked.png

Totals are easy to compare. The mix is not: does Nashik sell a bigger share of coffee than Pune? Nashik's bar is short, and only the bottom segment starts at the same baseline, so the other segments "float".

The fix: a 100% stacked bar chart. Divide each row by its own total so every bar is 100% tall.

share = df.div(df.sum(axis=1), axis=0) * 100
print(share.round(1))
ax = share.plot(kind="bar", stacked=True, rot=0, title="Sales mix by stall (%)")
ax.set_ylabel("% of units")
ax.legend(loc="upper left", bbox_to_anchor=(1, 1))
ax.figure.savefig("stacked100.png", bbox_inches="tight")
        Chai  Coffee  Snacks
Pune    56.5    15.2    28.3
Nashik  56.8    24.3    18.9
Mumbai  50.7    27.9    21.3

stacked100.png

  • df.sum(axis=1) adds across each row (a total per stall). df.div(totals, axis=0) divides each row by its own total (axis=0 lines the totals up with the row index).
  • Nashik is 24.3% coffee, Pune only 15.2%; Pune sells the biggest share of snacks.
  • bbox_to_anchor=(1, 1) with loc="upper left" puts the legend just outside the plot so it can't hide a bar.
  • Stacked = totals (and rough parts); 100% stacked = the mix.

Heatmap: patterns across two categories

Cups sold at the Pune stall for every day of the week and every hour from 7 am to 9 pm:

import sys; sys.tracebacklimit = 0
import matplotlib.pyplot as plt
import numpy as np
rng = np.random.default_rng(32)
days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
hours = list(range(7, 22))                       # 7 am to 9 pm
rush = np.array([1, 3, 6, 5, 3, 2, 2, 3, 3, 4, 6, 7, 5, 3, 2])
cups = rush * [[9], [9], [9], [9], [10], [14], [15]] + rng.integers(0, 6, (7, 15))
print(cups.shape)
print(cups)
(7, 15)
[[ 14  27  59  48  29  20  19  28  30  40  56  68  49  32  22]
 [ 13  30  58  50  29  21  19  32  30  39  57  64  50  29  20]
 [  9  30  57  47  30  18  22  27  32  37  55  66  46  32  22]
 [  9  28  56  48  31  21  23  29  27  38  54  63  45  27  19]
 [ 13  32  60  53  30  20  25  35  30  43  62  73  52  35  25]
 [ 16  43  85  74  46  31  32  44  46  59  89  98  70  44  33]
 [ 18  46  91  78  45  31  32  48  46  65  94 107  79  50  32]]

(The data is built by broadcasting from episode 10: a row of hourly "rush" levels times a column of day multipliers, plus random noise.)

The obvious attempt is the table itself: 105 numbers. A table is great for looking up one value and terrible for seeing a pattern.

The fix: a heatmap, a grid of cells coloured by value.

fig, ax = plt.subplots(figsize=(10, 4))
im = ax.imshow(cups, cmap="YlOrBr")
ax.set_xticks(range(len(hours)), labels=hours)
ax.set_yticks(range(len(days)), labels=days)
ax.set(title="Cups sold by day and hour", xlabel="Hour of day")
fig.colorbar(im, label="Cups")
fig.savefig("heatmap.png", bbox_inches="tight")
print("busiest:", days[cups.argmax() // 15], hours[cups.argmax() % 15], "h")
busiest: Sun 18 h

heatmap.png

  • ax.imshow(array2d, cmap=...) ("image show") draws a 2-D array as coloured cells. "YlOrBr" is a sequential colormap: light yellow for low, dark brown for high.
  • set_xticks(positions, labels=...) puts the hour and day names on the axes.
  • cups.argmax() is the position of the largest value in the flattened array; // 15 gives its row and % 15 its column.
  • Two rush hours every day (about 9 am and 6 pm), both much darker at the weekend; the busiest cell is Sunday 6 pm. The owner knows when to add a second person at the counter.
import sys; sys.tracebacklimit = 0
import matplotlib.pyplot as plt
import numpy as np
rng = np.random.default_rng(7)
months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"]
stalls = ["Pune", "Nashik", "Mumbai", "Chennai", "Howrah", "Jaipur"]
sales = {s: (rng.integers(40, 90) + rng.normal(0, 6, 6).cumsum()).round() for s in stalls}

(Each stall starts at a random level and wanders: cumsum adds up random steps, a random walk.)

The obvious attempt: six lines on one chart.

fig, ax = plt.subplots()
for s in stalls:
    ax.plot(months, sales[s], label=s)
ax.legend(ncol=3)
ax.set_title("Daily cups (hundreds), six stalls")
fig.savefig("spaghetti.png")
print("saved spaghetti.png")
saved spaghetti.png

spaghetti.png

Why it fails: lines cross, and to follow one stall you keep looking back at the legend. This is a spaghetti chart. Two or three lines are fine; six is a plate of noodles.

The fix: small multiples, many small charts with the same axes, one per group.

fig, axs = plt.subplots(2, 3, figsize=(10, 5), sharex=True, sharey=True)
for ax, s in zip(axs.flat, stalls):
    for other in stalls:
        ax.plot(months, sales[other], color="lightgray", lw=1)
    ax.plot(months, sales[s], color="tab:blue", lw=2.5)
    ax.set_title(s)
fig.suptitle("Daily cups (hundreds): each stall against the rest")
fig.tight_layout()
fig.savefig("small_multiples.png")
print(axs.shape, "axes share one y scale")
(2, 3) axes share one y scale

small_multiples.png

  • sharex=True, sharey=True: every panel uses the same scale, so a taller line really means more cups. Without sharey, each panel stretches its own scale and small changes look huge.
  • axs.flat walks through the grid in order; zip pairs each Axes with a stall.
  • Grey lines for context, one thick blue line for the panel's stall (lw = line width).
  • Now: Mumbai fell from about 90 to 63, Chennai stayed lowest, Nashik held steady.

Data-ink ratio and chartjunk

import sys; sys.tracebacklimit = 0
import matplotlib.pyplot as plt
stalls = ["Pune", "Nashik", "Mumbai", "Chennai", "Howrah"]
cups = [57900, 36200, 81400, 44800, 52300]
fig, ax = plt.subplots(facecolor="khaki")
ax.set_facecolor("lavender")
ax.bar(stalls, cups, color=["red", "lime", "blue", "magenta", "cyan"],
       edgecolor="black", linewidth=3, hatch="//")
ax.grid(True, color="black", linewidth=1.5)
ax.set_title("CUPS SOLD!!!", fontsize=22, fontweight="bold", color="purple")
fig.savefig("junk.png")
print("saved junk.png")
saved junk.png
  • Chartjunk: decoration that carries no information and gets in the way of the data (loud backgrounds, heavy grids, stripes, rainbow colours, 3-D effects). The word was coined by the statistician and designer Edward Tufte.
  • Data-ink ratio (also Tufte's term): the share of a chart's ink that shows actual data. Push it up: remove whatever doesn't help the reader.

Preattentive attributes and colour for meaning

Find the red car in a parking lot of grey cars: instant. Find the car whose plate starts with MH12: you must read every plate. Preattentive attributes are features the brain notices before paying attention: colour (hue), lightness, size, length, position, shape, orientation. A good chart uses one of them for the thing that matters and keeps everything else quiet.

fig, ax = plt.subplots()
colors = ["lightgray"] * 5
colors[0] = "tab:orange"                      # the stall we are talking about
bars = ax.bar(stalls, cups, color=colors)
ax.bar_label(bars, labels=[f"{c:,}" for c in cups])
ax.spines[["top", "right", "left"]].set_visible(False)
ax.set_yticks([])
ax.set_title("Pune is 2nd of 5 stalls in cups sold")
fig.savefig("clean.png")
print("saved clean.png")
saved clean.png
Chartjunk Clean
junk.png clean.png
  • Colour for meaning: grey for everything, one colour for the one thing the chart is about. Colour should mean something, never decorate.
  • ax.bar_label(bars, labels=...) writes each value on its bar, so the y axis can go (set_yticks([])).
  • Spines are the border lines around the plot area; ax.spines[[...]].set_visible(False) hides them.
  • The title states the message ("Pune is 2nd of 5"), not just the topic.

Colour-blind safe charts (accessibility)

About 1 in 12 men and 1 in 200 women are colour-blind, and red-green colour blindness is the most common kind (Cleveland Clinic figures, via Live Science). Accessibility means a chart everyone can read.

import sys; sys.tracebacklimit = 0
import matplotlib.pyplot as plt
from matplotlib.colors import to_rgb
for name in ["tab:red", "tab:green", "tab:blue", "tab:orange"]:
    r, g, b = to_rgb(name)
    print(f"{name:11} lightness {0.299*r + 0.587*g + 0.114*b:.2f}")
tab:red     lightness 0.36
tab:green   lightness 0.44
tab:blue    lightness 0.39
tab:orange  lightness 0.60
  • to_rgb turns a colour name into red, green and blue amounts from 0 to 1.
  • 0.299 R + 0.587 G + 0.114 B is a standard weighting for how light a colour looks to people (luma). Red and green are almost equally light, so without hue they look alike.
import sys; sys.tracebacklimit = 0
import matplotlib.pyplot as plt
import numpy as np
months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"]
target = [9000, 9000, 9500, 9500, 10000, 10000]
pune = [7900, 8800, 9400, 10100, 11800, 9900]
fig, ax = plt.subplots()
ax.plot(months, target, color="tab:green", lw=3)
ax.plot(months, pune, color="tab:red", lw=3)
fig.savefig("red_green.png")
gray = plt.imread("red_green.png")[..., :3] @ [0.299, 0.587, 0.114]
plt.imsave("red_green_gray.png", gray, cmap="gray")
print("saved red_green.png and red_green_gray.png")
saved red_green.png and red_green_gray.png

plt.imread reads the PNG as an array (height × width × channels); [..., :3] keeps red, green, blue; @ [0.299, 0.587, 0.114] is a matrix multiplication that gives one lightness per pixel; plt.imsave(..., cmap="gray") saves it in greyscale.

The fix: never let colour be the only clue.

fig, ax = plt.subplots()
ax.plot(months, target, color="tab:blue", lw=2, ls="--", marker="s")
ax.plot(months, pune, color="tab:orange", lw=3, marker="o")
ax.text(5.1, 10050, "target", color="tab:blue", va="bottom")
ax.text(5.1, 9850, "Pune", color="tab:orange", va="top")
ax.set_xlim(-0.3, 5.9)
fig.savefig("safe.png")
gray = plt.imread("safe.png")[..., :3] @ [0.299, 0.587, 0.114]
plt.imsave("safe_gray.png", gray, cmap="gray")
print("saved safe.png and safe_gray.png")
saved safe.png and safe_gray.png
Red vs green Its greyscale copy Blue/orange + dashes + labels Its greyscale copy
red_green.png red_green_gray.png safe.png safe_gray.png
  • Blue and orange: a pair most colour-blind viewers can tell apart, and very different in lightness.
  • Line style (ls="--" dashed) and markers as a second and third clue.
  • Direct labels: names written at the end of each line (va = vertical alignment), so no legend is needed.
  • matplotlib's style "tableau-colorblind10" and seaborn's "colorblind" palette (episode 33) give colour-blind safe colours.

Misleading charts 1: the truncated axis

import sys; sys.tracebacklimit = 0
import matplotlib.pyplot as plt
stalls = ["Pune", "Nashik"]
cups = [10100, 9800]
fig, axs = plt.subplots(1, 2, figsize=(9, 4))
axs[0].bar(stalls, cups, color="tab:red")
axs[0].set_ylim(9700, 10150)
axs[0].set_title("y axis starts at 9,700")
axs[1].bar(stalls, cups, color="tab:blue")
axs[1].set_title("y axis starts at 0")
fig.tight_layout()
fig.savefig("truncated.png")
print(f"real gap: {cups[0]/cups[1] - 1:.1%}")
print(f"bar heights on the left: {(cups[0]-9700)/(cups[1]-9700):.1f} times")
real gap: 3.1%
bar heights on the left: 4.0 times

truncated.png

A truncated axis starts above zero. A bar's length is supposed to be its value, so cutting off the bottom makes a 3.1% gap look like 4 times. Rule: bar charts always start at zero. Line charts may zoom in, because a line's meaning is its slope, not its length, but label the axis clearly.

Misleading charts 2: dual-axis abuse

import sys; sys.tracebacklimit = 0
import matplotlib.pyplot as plt
months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"]
cups = [7900, 8800, 9400, 10100, 11800, 9900]
rev = [134300, 149600, 159800, 191900, 224200, 188100]
fig, axs = plt.subplots(1, 2, figsize=(10, 4))
for ax, lim, story in [(axs[0], (0, 600000), "Revenue flat?"),
                       (axs[1], (100000, 230000), "Revenue soars?")]:
    ax.plot(months, cups, color="tab:blue")
    ax.set_ylim(0, 12500)
    ax2 = ax.twinx()
    ax2.plot(months, rev, color="tab:red")
    ax2.set_ylim(*lim)
    ax.set_title(story)
fig.tight_layout()
fig.savefig("dual_abuse.png")
print("same data, two stories")
same data, two stories

dual_abuse.png

Same numbers, only the right axis limits changed (*lim unpacks the pair into two arguments). With two y axes the author chooses both scales, so where the lines sit and where they cross means nothing: dual-axis abuse. Safer: two charts stacked with a shared x axis, or both series as percent change from the first month on one axis. If you must use twin axes, label and colour each scale and never read meaning into crossings.

Common mistakes

Code / habit Real error / symptom Why Fix
pie of 8 similar slices no error; ranking unreadable angles are hard to compare sorted barh
stacked bars to compare the mix no error; floating segments totals differ 100% stacked: df.div(df.sum(axis=1), axis=0)
6+ lines on one axes no error; spaghetti crossing lines, legend hunting small multiples, sharey=True
small multiples without sharey no error; panels look equal each panel has its own scale sharey=True
ax.set_ylim(9700, ...) on bars no error; 3% looks like 4× bar length = value bars start at 0
red vs green as the only clue no error; unreadable for many similar lightness blue/orange + dashes + markers + labels
rainbow colours, heavy grid, stripes no error; tiring, slow to read chartjunk grey + one highlight, remove clutter
twin axes with chosen limits no error; false story each scale is free stacked subplots or % change
legend covering bars hidden data legend placed inside bbox_to_anchor=(1, 1)

Practice

1. Phone time shares: Videos 34%, Chats 27%, Games 15%, News 10%, Maps 8%, Camera 6%. Draw them as sorted bars, biggest on top.

Solution
import sys; sys.tracebacklimit = 0
import matplotlib.pyplot as plt
apps = ["Videos", "Chats", "Games", "News", "Maps", "Camera"]
share = [34, 27, 15, 10, 8, 6]
fig, ax = plt.subplots()
order = sorted(range(len(apps)), key=lambda i: share[i])
ax.barh([apps[i] for i in order], [share[i] for i in order], color="tab:blue")
ax.set(title="Share of phone time (%)", xlabel="% of time")
fig.savefig("p1.png", bbox_inches="tight")
print([apps[i] for i in order])
['Camera', 'Maps', 'News', 'Games', 'Chats', 'Videos']

barh draws the first item at the bottom, so sorting from smallest to biggest puts the biggest on top.

2. Online and counter orders per month: Jan 120 / 480, Feb 150 / 450, Mar 210 / 390. Which chart shows how the online share changed? Compute the shares.

Solution

A composition-over-time question: a 100% stacked bar per month (or a line of the online share).

import pandas as pd
df = pd.DataFrame({"online": [120, 150, 210], "counter": [480, 450, 390]}, index=["Jan", "Feb", "Mar"])
share = df.div(df.sum(axis=1), axis=0) * 100
print(share.round(1))
     online  counter
Jan    20.0     80.0
Feb    25.0     75.0
Mar    35.0     65.0

Then share.plot(kind="bar", stacked=True, rot=0).

3. Pune 10,100 and Nashik 9,800 cups, drawn as bars with the y axis starting at 9,000. How many times taller does Pune's bar look?

Solution
cups = [10100, 9800]
print(f"{(cups[0]-9000)/(cups[1]-9000):.2f}")
1.38

Pune's bar looks 1.38 times as tall (1,100 vs 800 visible units), although the real difference is only 3.1%.

4. Match each question to a purpose and a chart: (a) Is there a link between temperature and cold-drink sales? (b) How are delivery times spread? (c) Which of 12 branches had the highest profit? (d) How did daily visitors change over a year?

Solution

(a) relationship → scatter plot; (b) distribution → histogram or box plot; (c) comparison → sorted (horizontal) bars; (d) trend → line chart.

5. Why is a red "bad" bar next to a green "good" bar risky, and what two changes fix it?

Solution

tab:red and tab:green have lightness 0.36 and 0.44, nearly the same, so viewers with red-green colour blindness (the most common kind) and greyscale printouts can't tell them apart. Use colours that differ in lightness (blue/orange) and a second clue: labels, patterns, markers or position.

Quick quiz

"How did the share of online orders change month by month at three stalls?" Which chart fits best?

A. A pie chart per month B. 100% stacked bars, one per stall per month C. A scatter plot D. A histogram

Answer

B. It's a composition (share) question across categories and time. Eighteen pies can't be compared; a small-multiple line of the share per stall would also work.

Interview questions

  1. How do you choose a chart? Start from the question's purpose: comparison, composition, distribution, relationship or trend.
  2. When is a pie chart acceptable? For two or three clearly different parts of a whole; otherwise sorted bars.
  3. Stacked vs 100% stacked bars? Stacked compares totals; 100% stacked compares the mix (shares) when totals differ.
  4. What is a heatmap good for? Showing a pattern in a numeric value across two categorical (or binned) dimensions.
  5. What are small multiples and why share axes? Many small charts with the same scales, one per group; shared axes make comparisons fair.
  6. What is the data-ink ratio? The share of ink that shows data; maximise it by removing chartjunk (Tufte).
  7. What are preattentive attributes? Features seen before conscious attention (colour, size, position, length, shape); use one to highlight the key point.
  8. How do you make charts colour-blind friendly? Avoid red/green as the only distinction; use palettes like blue/orange or tableau-colorblind10, plus labels, markers and line styles.
  9. Why must bar charts start at zero? Bar length encodes value; a truncated axis exaggerates differences.
  10. What's wrong with dual-axis charts? Each axis scale is arbitrary, so crossings and relative positions can be manipulated.

Glossary

Term Meaning Example
Chart purpose The one question a chart answers "Which stall sold most?"
Comparison Which is bigger? bars of stall totals
Composition What the whole is made of share of chai in sales
Distribution How values are spread bill histogram
Relationship Whether two numbers move together wait vs rating scatter
Trend Change over time cups per month line
Pie chart Circle cut into slices proportional to parts ax.pie(sold, labels=items)
Baseline The common starting line of bars the y = 0 line
Stacked bar chart Parts stacked on top of each other in one bar df.plot(kind="bar", stacked=True)
Segment One part of a stacked bar the coffee part
100% stacked bar chart Every bar scaled to 100% to compare the mix df.div(df.sum(axis=1), axis=0) * 100
df.div(..., axis=0) Divide each row by a matching value row totals
Heatmap Grid of cells coloured by value day × hour cups
imshow Draws a 2-D array as coloured cells ax.imshow(cups, cmap="YlOrBr")
Sequential colormap Light-to-dark colours for low-to-high values "YlOrBr", "Blues"
argmax Position of the largest value cups.argmax()
Random walk A series built by adding random steps .cumsum() of noise
Spaghetti chart Too many crossing lines on one chart six stalls
Small multiples Many small charts with the same axes, one per group plt.subplots(2, 3, sharey=True)
axs.flat Walks through a grid of axes in order zip(axs.flat, stalls)
Chartjunk Decoration that carries no information stripes, loud backgrounds
Data-ink ratio Share of ink that shows data remove the heavy grid
Preattentive attribute Feature the eye notices before attention one orange bar among grey
Colour for meaning Colour only where it means something highlight Pune
bar_label Writes values on bars ax.bar_label(bars)
Spines Border lines around the plot area ax.spines[["top", "right"]]
Colour blindness Reduced ability to tell some colours apart red-green, ~1 in 12 men
Accessibility Making a chart readable for everyone blue/orange + labels
Lightness (luma) How light a colour looks 0.299R + 0.587G + 0.114B
to_rgb Colour name → (red, green, blue) to_rgb("tab:red")
Direct label Name written next to its line, not in a legend "target", "Pune"
Line style Solid, dashed, dotted lines ls="--"
tableau-colorblind10 matplotlib style with a colour-blind safe palette plt.style.use("tableau-colorblind10")
Misleading chart A chart whose design suggests a false story truncated bars
Truncated axis An axis that doesn't start at zero set_ylim(9700, 10150)
Dual-axis abuse Using two free y scales to suggest a false story "Revenue soars?"
Percent change Change relative to a starting value (x − Jan) / Jan × 100

Summary

  • Question first: comparison, composition, distribution, relationship or trend; the purpose picks the chart.
  • Pie only for 2-3 clearly different parts; otherwise sorted bars. Bars for categories, lines for time.
  • Stacked bars show totals; 100% stacked bars show the mix.
  • A heatmap turns a 2-D table into colour; small multiples (shared axes) beat spaghetti.
  • Maximise the data-ink ratio, remove chartjunk, use one highlight colour (preattentive attributes) and a title that states the message.
  • Colour-blind safe: never colour alone; blue/orange, dashes, markers, direct labels.
  • Bars start at zero; be suspicious of dual axes.
  • Next episode: seaborn for statistical plots.

Sources for facts in this episode: Edward Tufte coined "chartjunk" and uses the term "data-ink ratio" (Wikipedia: Edward Tufte); colour blindness affects about 1 in 12 males and 1 in 200 females, red-green being most common (Live Science, citing Cleveland Clinic).