Charts in Python that people in a business actually read: matplotlib, seaborn and Plotly

TL;DR

Difficulty: Intermediate

Write the chart's sentence first, then the code that makes it visible.

  • matplotlib is the engine; pandas .plot() and seaborn hand you matplotlib objects; Plotly is for exploring on screen.
  • Decisions that never change go into one .mplstyle file: size, fonts, borders, the Okabe and Ito colours, svg.fonttype none.
  • Decisions for one chart come from its sentence: the right measure, sorted, grey plus one accent, numbers on the bars, a break even line, a source line.
  • Check colour contrast in code: 3:1 for bars and lines. Save SVG for screens and PNG at 200 dpi for email.
  • A short preflight function catches a missing title, a legend, pale colours and rotated labels before a chart goes out.

Every analysis ends in a chart that someone else has to read in about five seconds. This chapter builds one business chart three times in Python, the default, a decluttered and focused version and an interactive one, and turns the rules of good charts into a style sheet and a check you write once and reuse.

Every analysis ends in a chart that someone else has to read. Áine, the founder of Ardmore Home, the invented Sligo homeware shop that runs through this series, does not read code and does not read tables of 48 numbers. She reads a picture for about five seconds, and in those five seconds the picture either answers her question or it does not. Her question has not changed since the first chapter. Which channel really pays back, and where should next month's budget go?

This chapter is about making that picture in Python. It covers the four libraries you will meet (matplotlib, the plotting built into pandas, seaborn and Plotly), how they fit together, and how to turn the principles of the data storytelling series into code you write once and reuse for years. One chart is built three times: the default you get for free, a decluttered and focused version for Áine, and an interactive version for Darragh, the analyst, to explore. All the code is here, and it runs.

It builds on the chapter on time series, where the monthly data came from, and on group by and pivot tables, where the summaries came from. If you have not set up Python yet, the first chapter does that.

If you only read one section

This part is for the person who commissions the chart, not the person who codes it.

  • A chart is a sentence with a picture attached. Ask for the sentence first. "Paid social prospecting returns 76c of margin for every €1 it costs" is a finding. "Spend and revenue by campaign" is a topic. If the analyst cannot write the sentence, the chart is not ready, however good it looks.
  • The default chart that any library produces is an exploration chart. It is grand for the analyst's own eyes. It is not fine for a decision. Expect the version you see to look calmer than a default: fewer lines, one colour that means "look here", the numbers written on the chart, a title that states the point.
  • Ask whose numbers they are. A revenue figure from Meta's own report, a revenue figure from Google Analytics and a revenue figure from the shop's order export are three different numbers for the same month. A good chart says in a small line underneath which one it shows.
  • Interactive is for exploring, static is for deciding. A dashboard you can hover over is a good place for the analyst to find the story. The decision should be made from one static chart with the story written on it.
  • The style should be written down once. In Python that is a small style file that every chart loads, so every chart from the business looks like it came from the same hand, and nobody spends Friday afternoon recolouring bars.

In the example below, the finished chart tells Áine that one campaign type lost €5,014 of margin on first orders in a single quarter. The default chart, made from exactly the same numbers, hides it.

Write the sentence before you write the plot call

Here is the idea I would put above everything else in this chapter. The title of a business chart is not decoration added at the end. It is the specification. You write the sentence first, and then you write the code that makes the sentence visible. Every later decision (which chart type, which order, which colour, what to label) is settled by asking "does this help the reader see the sentence?"

This turns charting from taste into a test. A chart is finished when a reader who sees only the picture for five seconds can repeat the sentence back to you. The idea comes straight from the storytelling series, which calls it the Big Idea and shows how to write titles that make the point. What changes in code is that the sentence can live in the script, next to the numbers it depends on, and it can even be checked against them.

Example: Darragh writes the sentence first. Before opening a notebook, Darragh writes the question and his draft answer at the top of the cell:

# Question:  which paid campaign type really pays back?
# Measure:   gross margin earned per €1 of ad spend, July to September 2025
# Sentence:  "Paid social prospecting returns 76c per €1.
#             Every other paid campaign pays back."

The sentence names a campaign type, a number and a comparison. That already decides most of the chart. The measure is a ratio, so one bar per campaign type. There is a comparison with break even, so a reference line at €1. One campaign type is the point, so one colour for it and grey for the rest. If the numbers later say something else, he changes the sentence, not the colour of the bars.

Four libraries, one engine underneath

Python has many charting libraries. For business work you need to know four, and three of them share one engine.

  • matplotlib is the foundation, started by John Hunter in 2002 and described in a 2007 paper12. It draws everything: lines, bars, text, the axes. It is very flexible and its defaults are plain, so most of the work is telling it what to leave out.
  • pandas plotting is a thin layer on top of matplotlib. Call .plot() on a DataFrame and pandas makes a matplotlib chart from it, with the index as the x axis and one line or bar per column3. It is the fastest way to look at your data, and it returns a matplotlib object you can keep working on.
  • seaborn is a library for statistical charts, also built on matplotlib, written by Michael Waskom4. It takes a tidy DataFrame (one row per observation) and a few column names, and handles grouping, small multiples and statistical summaries such as histograms and density curves for you.
  • Plotly is the odd one out. It does not use matplotlib. It builds charts in the web browser with JavaScript, so the reader can hover, zoom and switch series on and off, and you save them as HTML files5.

In Wes McKinney's Python for Data Analysis, chapter 9 covers matplotlib, pandas and seaborn, and names Altair, Bokeh and Plotly only briefly as tools for interactive web graphics1. That is still the right weighting for the static charts a business sends around. Plotly earns its place as the analyst's exploration tool.

LibraryBest forWhat you getWatch out for
pandas .plot()A quick look while you workA matplotlib chart in one lineDefaults made for the analyst, not the reader
matplotlibThe finished chart that leaves the buildingFull control of every element, SVG and PNGPlain defaults, two styles of code in tutorials
seabornDistributions, many groups, small multiplesStatistical views from a tidy DataFrameIts own figure handling in the figure level functions
PlotlyExploring on screen, hovering for detailAn interactive HTML fileLarge files, static export needs extra tools

Example: which library for which of Darragh's four charts. In a normal month Darragh makes four kinds of chart. The quick check that the September export loaded correctly is a pandas .plot() that nobody else sees. The one chart that goes to Áine with the budget recommendation is matplotlib with the house style. The view of order values for all six channels side by side is seaborn, finished with matplotlib. The page where Darragh hovers over twelve months of campaign data looking for the month things changed is Plotly. The flow below is the same decision, written as a path you can follow for any chart.

Tap or click to enlarge

The versions used here are the ones current when this chapter was written in October 2025: matplotlib 3.10, pandas 2.3, seaborn 0.13.2, Plotly 6.3 and NumPy 2.36. The code runs on Python 3.13, and on Python 3.14, which was released on 7 October 20257.

python -m pip install "matplotlib>=3.10" "pandas>=2.3" "seaborn>=0.13.2" "plotly>=6.3"

The example data: twelve months of paid campaigns

Ardmore Home sells about 48,000 orders a year to about 21,000 customers, at an average order value of €66 and a gross margin of 52%. Darragh has already done the hard part in earlier chapters: he loaded the exports, removed test orders and netted off refunds, joined the shop's orders to the GA4 session source and to the Google Ads and Meta spend, and resampled everything to months.

Three traps from those steps decide whether the chart is honest, and none of them is visible in the chart itself.

  • Whose revenue. Meta and Google Ads each report the revenue they believe they caused, under their own attribution windows. Add the two together and you usually get more revenue than the shop took. Darragh uses one source for every campaign: the shop's own orders, net of refunds, matched to a campaign by the session source GA4 recorded.
  • Refunds as separate rows. The shop export lists a refund as its own negative row, sometimes weeks after the order. Chart gross sales and a campaign that brings in many returners looks better than it is.
  • Month boundaries. The order export is in UTC and the GA4 property is set to Europe/Dublin. In summer, an order placed at 00:30 on 1 August in Sligo is 23:30 on 31 July in UTC. Group by the wrong clock and orders slide between months.

So the data below stands for the clean, joined result. It is generated in code with a fixed seed so you can run every line and get the same numbers. Four campaign types, twelve months, spend and revenue in euro.

Example: generating Ardmore's monthly campaign data.

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

rng = np.random.default_rng(10)

# Twelve months, October 2024 to September 2025, as month start dates
months = pd.date_range("2024-10-01", periods=12, freq="MS")

# Average monthly spend in euro, and the shop revenue each euro brings in
# (shop orders net of refunds, matched to the campaign by GA4 session source)
campaigns = {
    "Paid search, brand":       {"spend": 1590, "roas": np.full(12, 9.5)},
    "Paid search, generic":     {"spend": 8190, "roas": np.full(12, 3.45)},
    "Paid social, prospecting": {"spend": 7170, "roas": np.linspace(2.3, 1.35, 12)},
    "Paid social, retargeting": {"spend": 2390, "roas": np.full(12, 4.4)},
}
# Seasonality: November and December busier, January and February quieter
season = np.array([1.0, 1.25, 1.45, 0.8, 0.85, 0.95,
                   0.95, 0.95, 0.95, 0.95, 0.95, 1.0])

rows = []
for name, c in campaigns.items():
    spend = c["spend"] * season * rng.normal(1, 0.05, 12)
    revenue = spend * c["roas"] * rng.normal(1, 0.04, 12)
    for month, s, r in zip(months, spend, revenue):
        rows.append({"month": month, "campaign": name,
                     "spend": round(s, 2), "revenue": round(r, 2)})

monthly = pd.DataFrame(rows)
print(monthly.head(3))
#        month            campaign    spend   revenue
# 0 2024-10-01  Paid search, brand  1502.28  14075.41
# 1 2024-11-01  Paid search, brand  1915.45  18159.38
# 2 2024-12-01  Paid search, brand  2215.38  20227.58

The measure in Darragh's sentence is gross margin per euro of spend. Revenue alone flatters every channel, because the shop keeps only 52% of it after the cost of the goods. The measure is a simple ratio (Foundations: ratios and rates):

M=m×RSM = \frac{m \times R}{S}

where MM is the gross margin earned per €1 of ad spend, mm is the gross margin rate (0.52 for Ardmore), RR is the revenue from the campaign's orders, net of refunds, and SS is the ad spend. M=1M = 1 is break even on the first order: every euro spent comes back as exactly one euro of margin.

Example: margin per €1 for the third quarter. Darragh sums July to September by campaign type with a group by:

MARGIN = 0.52  # Ardmore's gross margin

monthly["margin_per_euro"] = MARGIN * monthly["revenue"] / monthly["spend"]

q3 = (monthly[monthly["month"] >= "2025-07-01"]
      .groupby("campaign")[["spend", "revenue"]].sum())
q3["margin_per_euro"] = MARGIN * q3["revenue"] / q3["spend"]
print(q3.round(2))
#                              spend   revenue  margin_per_euro
# campaign
# Paid search, brand         4455.16  41655.08             4.86
# Paid search, generic      24343.99  83780.67             1.79
# Paid social, prospecting  20494.84  29771.24             0.76
# Paid social, retargeting   6900.04  30168.72             2.27

For paid social prospecting: M=0.52×29,771.24/20,494.84=15,481.04/20,494.84=0.76M = 0.52 \times 29{,}771.24 / 20{,}494.84 = 15{,}481.04 / 20{,}494.84 = 0.76. Ardmore spent €20,495 and got €15,481 of margin back on the first orders: a shortfall of €5,014 in one quarter. That is the number the chart has to carry.

The figure and axes model

Before any styling, one idea makes matplotlib far less confusing. Every chart is made of two kinds of object. The Figure is the whole canvas: its size, its background, the file you save. An Axes (always with an s, even when there is one) is one plot area inside it, with its own x axis, y axis, title, bars and lines. A Figure can hold one Axes or many8.

There are also two ways of writing matplotlib code, and tutorials mix them freely, which is the main source of confusion. The implicit style calls functions on plt (plt.bar, plt.title) and lets matplotlib guess which chart you mean. The explicit style asks for the objects once and then calls methods on them: fig, ax = plt.subplots(), then ax.bar, ax.set_title. The matplotlib documentation describes both and recommends the explicit one for anything beyond a quick look8. Use the explicit style in every script that makes a chart someone else will see. It never guesses, so a chart in a loop or in a function always lands where you meant it.

Example: one Figure, two Axes. Darragh wants spend and margin per euro next to each other, sharing the list of campaign types:

fig, (ax_spend, ax_return) = plt.subplots(
    1, 2, figsize=(9, 3), sharey=True, layout="constrained")

ax_spend.barh(q3.index, q3["spend"])
ax_spend.set_title("Spend, July to September (€)")

ax_return.barh(q3.index, q3["margin_per_euro"])
ax_return.set_title("Margin per €1")

print(type(fig).__name__, len(fig.axes))
# Figure 2

plt.subplots returns the Figure and the Axes. sharey=True makes both panels use the same y axis, so the campaign names appear once. layout="constrained" asks matplotlib to fit titles and labels without overlapping. Everything after that line talks to a named object, so there is never any doubt which panel a title belongs to.

pandas fits into the same model. df.plot() returns a matplotlib Axes, and ax.figure gives you its Figure, so a pandas chart can be finished with exactly the same methods.

Version one: the default chart

The quickest chart of Darragh's table is one line of pandas. It is worth looking at closely, because almost every business chart that disappoints started here and stopped too early.

Example: the default.

ax = q3[["spend", "revenue"]].plot.bar()
print(ax.figure.get_size_inches(), ax.figure.dpi)
# [6.4 4.8] 100.0

What comes out is a grouped bar chart: two bars per campaign type, blue for spend and orange for revenue, in alphabetical order, with a legend in the corner, the campaign names turned on their side and cut off, and no title. Matplotlib's default figure is 6.4 by 4.8 inches at 100 dots per inch, so 640 by 480 pixels.

Nothing in it is wrong. It shows the data. But read it as Áine would:

  1. It answers a different question. It shows spend and revenue, so the reader has to divide one bar by the other in their head, four times, and then multiply by the margin. The sentence is about margin per euro, which is not on the chart at all.
  2. The order is the alphabet. Alphabetical order is the order of the data, not the order of the argument.
  3. The legend makes the eye travel. To know which bar is spend you look at the corner and back.
  4. The labels are rotated because the names do not fit under vertical bars. Rotated text is slow to read.
  5. The orange is too pale to see well. Its contrast against white is 2.5 to 1, below the 3 to 1 that accessibility guidance asks of chart elements (more on that below).
  6. There is no title, so the reader has to work out what the chart is for.
  7. There is no source. Revenue from where, net of what?

Every one of these has a fix, and each fix is a few lines. The trick is to sort them into two groups: the fixes you make once, for every chart, and the fixes you make for this chart.

Write the house style once

Decluttering is mostly a style decision. Removing the top and right borders, choosing the font size, putting titles on the left, dropping the legend frame: these are the same for every chart a business makes. Do them once, in a file. Focus, on the other hand, is an editorial decision: which bar is the point, what the title says. That is per chart. Keeping the two apart is what makes a chart routine fast, and it is the advice behind the chart style guide chapter and the decluttering chapter.

In matplotlib every default lives in a dictionary called rcParams (runtime configuration parameters). A style sheet is a small text file with the extension .mplstyle that sets some of them. plt.style.use("file.mplstyle") loads it for the session, and plt.style.context(...) applies it to one block of code only9. Put the file next to your notebooks, or in a shared folder, and every chart Ardmore makes starts from the same place.

Example: Ardmore's style sheet. Darragh writes the file from Python, so it is part of the code and goes into version control with it:

from pathlib import Path

Path("ardmore.mplstyle").write_text("""
figure.figsize: 7, 4.2
figure.dpi: 100
figure.constrained_layout.use: True
savefig.dpi: 200
svg.fonttype: none
font.family: sans-serif
font.size: 12
axes.titlesize: 14
axes.titleweight: bold
axes.titlelocation: left
axes.spines.top: False
axes.spines.right: False
axes.edgecolor: 595959
axes.labelcolor: 404040
axes.grid: False
xtick.color: 595959
ytick.color: 595959
legend.frameon: False
axes.prop_cycle: cycler('color', ['0072B2', 'D55E00', '009E73', 'CC79A7', 'E69F00', '56B4E9', 'F0E442', '000000'])
""")

plt.style.use("ardmore.mplstyle")

Line by line, the decisions are:

  • figure.figsize: 7, 4.2 with figure.dpi: 100. A chart 7 inches wide at 100 dots per inch is 700 pixels on screen, which is about the width of a report column. The reason for that pairing is explained in the section on saving below.
  • figure.constrained_layout.use: True fits titles and labels inside the canvas automatically.
  • savefig.dpi: 200 saves PNG files at twice the screen resolution, so they stay sharp on high resolution screens.
  • svg.fonttype: none keeps text in SVG files as real text. The matplotlib default is path, which turns every letter into a drawn shape9. That looks identical, but a screen reader cannot read it, nobody can search it, and nobody can correct a typo in it.
  • Title on the left, bold, larger. People read a chart the way they read a page, top left first, which is where the sentence belongs.
  • No top or right border, no grid, no legend frame. Each of these is ink that carries no data.
  • Dark grey for axes and labels instead of black, so the data stands out against its frame.
  • The colour cycle is the Okabe and Ito palette, a set of eight colours designed in 2002 to stay distinguishable for people with the common forms of colour vision deficiency10. Whenever a chart needs several colours, it takes them from this list in this order.

One more line is worth keeping in the same place: a small dictionary that gives colours a role, not just a value.

COLOURS = {
    "accent": "#D55E00",     # Okabe and Ito vermillion: "look here"
    "context": "#8C8C8C",    # grey: everything that is not the point
    "text": "#404040",       # labels and numbers
    "reference": "#595959",  # break even lines, source notes
}

The roles matter more than the hex codes. "Accent" always means "this is the point of the chart", so it appears once per chart at most. "Context" is everything else. This is the focus with one colour idea from the storytelling series, made into a rule the code follows.

Colour that everyone can read

Two things go wrong with colour in business charts. Colours are chosen that some readers cannot tell apart, and colours are chosen that are too pale to see against the background. The first is solved by a palette designed for it, such as Okabe and Ito. The second needs a number, and it can be checked in code.

The Web Content Accessibility Guidelines (WCAG) set a minimum contrast of 3 to 1 against neighbouring colours for the graphical parts of a chart that a reader needs to understand it, and 4.5 to 1 for normal text11. The colour chapter explains why. Contrast is calculated from the relative luminance of the two colours, which is how bright each looks to the eye:

C=L1+0.05L2+0.05C = \frac{L_1 + 0.05}{L_2 + 0.05}

This is another ratio (Foundations: ratios and rates), where CC is the contrast ratio, L1L_1 is the relative luminance of the lighter colour and L2L_2 that of the darker one, each between 0 (black) and 1 (white). Relative luminance weights the red, green and blue channels by how sensitive the eye is to each, after undoing the gamma curve of the screen11. The ratio runs from 1 to 1 (no contrast) to 21 to 1 (black on white).

Example: checking Ardmore's colours against white. Darragh turns the WCAG definition into two small functions:

def relative_luminance(hex_colour):
    """WCAG relative luminance of a colour such as '#D55E00'."""
    rgb = [int(hex_colour.lstrip("#")[i:i + 2], 16) / 255 for i in (0, 2, 4)]
    linear = [c / 12.92 if c <= 0.04045 else ((c + 0.055) / 1.055) ** 2.4
              for c in rgb]
    return 0.2126 * linear[0] + 0.7152 * linear[1] + 0.0722 * linear[2]

def contrast(colour, background="#FFFFFF"):
    lighter, darker = sorted([relative_luminance(colour),
                              relative_luminance(background)], reverse=True)
    return (lighter + 0.05) / (darker + 0.05)

for role, colour in COLOURS.items():
    print(f"{role:10} {colour}  {contrast(colour):.2f}:1")
# accent     #D55E00  3.87:1
# context    #8C8C8C  3.36:1
# text       #404040  10.37:1
# reference  #595959  7.00:1

Worked through for the vermillion accent: its relative luminance is about 0.221, white's is 1, so C=(1+0.05)/(0.221+0.05)=1.05/0.271=3.87C = (1 + 0.05) / (0.221 + 0.05) = 1.05 / 0.271 = 3.87. It passes 3 to 1 for a bar. The grey passes too, at 3.36 to 1. That is not an accident: the more familiar light grey #BBBBBB scores only 1.92 to 1, which is why Darragh chose a darker one.

The same check shows a trap inside the Okabe and Ito palette itself. Its orange (#E69F00, 2.25 to 1), sky blue (#56B4E9, 2.31 to 1) and yellow (#F0E442, 1.32 to 1) are distinguishable from each other but too pale against white to carry data on their own. Its blue (#0072B2, 5.19 to 1) and vermillion pass. A palette being safe for colour vision deficiency and being readable on white are two separate tests. Run both. And when a colour is below 3 to 1, the fix is usually not a darker colour but a direct label in readable text, so the colour is no longer the only way to get the number.

Version two: decluttered and focused

With the style loaded and the colours checked, the per chart decisions are few. Each comes straight from the sentence.

Show the measure in the sentence

The sentence is about margin per euro, so the chart shows margin per euro: one bar per campaign type. The reader no longer divides anything.

Sort by the value and turn the bars

Sorting puts the bars in the order of the argument, from best to worst. Horizontal bars give the campaign names room to sit level and readable, so nothing is rotated. The chapter on amounts and proportions makes the case for both.

Grey for context, one colour for the point

Prospecting gets the accent. The other three bars are grey. The eye goes to the coloured bar before the reader has decided to look anywhere.

Put the numbers on the bars and the point in the title

Each bar gets its value written at its end with ax.bar_label12, so the axis with its tick marks can go. The title is the sentence, in two short lines.

Add the reference and the source

A dashed line at €1 marks break even, labelled in words. A small line at the foot says where the numbers come from, so the question "whose revenue" is answered before anyone asks it.

Example: Ardmore's paid campaign chart, finished.

data = q3["margin_per_euro"].sort_values()
highlight = "Paid social, prospecting"
colours = [COLOURS["accent"] if name == highlight else COLOURS["context"]
           for name in data.index]

fig_paid, ax = plt.subplots()
bars = ax.barh(data.index, data.values, color=colours, height=0.6)

# Break even: one euro of margin for every euro spent
ax.axvline(1, color=COLOURS["reference"], linewidth=1, linestyle=(0, (4, 3)))
ax.text(1.06, -0.75, "Break even: €1 of margin per €1 spent",
        color=COLOURS["reference"], fontsize=10, va="center")

# The numbers on the bars replace the x axis
ax.bar_label(bars, labels=[f"€{v:.2f}" for v in data.values],
             padding=4, color=COLOURS["text"],
             bbox={"facecolor": "white", "edgecolor": "none", "pad": 1})
ax.set_title("Paid social prospecting returns 76c per €1.\n"
             "Every other paid campaign pays back.")
ax.set_xlabel("Gross margin per €1 of ad spend, July to September 2025")
ax.spines[["left", "bottom"]].set_visible(False)
ax.tick_params(left=False, bottom=False, labelbottom=False)
ax.set_xlim(0, 5.6)
ax.set_ylim(-1.0, 3.5)

# Leave room at the foot for the source line
fig_paid.get_layout_engine().set(rect=(0, 0.07, 1, 0.93))
fig_paid.text(0.01, 0.015, "Source: shop orders net of refunds, by GA4 session "
         "source. Margin 52%.", fontsize=9, color=COLOURS["reference"])

A few details are worth a second look. sort_values() sorts from smallest to largest, and barh draws the first item at the bottom, so the largest bar ends up on top without any extra step. The white box behind each number keeps the break even line from running through it. The x limit of 5.6 leaves room for the label on the longest bar. The y limit of minus 1 makes space below the bars for the break even note. The layout engine call reserves the bottom 7% of the canvas for the source line, which constrained layout would otherwise not know about.

This is the version Áine sees, shown here with the blog's own chart component:

Horizontal bar chart of gross margin per euro of ad spend, July to September 2025, at Ardmore Home. Paid search brand returns €4.86, paid social retargeting €2.27, paid search generic €1.79 and paid social prospecting €0.76, the only campaign type below the break even of €1. Source: shop orders net of refunds, by GA4 session source, gross margin 52%. Tap or click to enlarge

Compare it with the default. The same four numbers sit underneath both. The default needs a reader to calculate. This one needs a reader to look. It also tells the truth more completely, because it states its measure, its period and its source.

It is also honest about a limit, and the text that goes with it should say so in one line: margin per euro on first orders measures what a campaign earns in the quarter, not what the customers it found will spend over the next two years. Prospecting is the campaign type most likely to find new customers who come back, and brand search and retargeting are the most likely to be credited for sales that would have happened anyway. The chart shows the first effect. It does not settle the second. Lifetime value gets its own chapter in the Marketing analytics in Python series.

Time on the x axis: the chart that answers "since when"

The bar chart answers "which". The first question Áine asks after reading it is "since when?", and that needs time on the x axis. The rules change slightly for a line chart. Bars must start at zero, because the reader compares their lengths. A line or a dot shows a value by its position, so it does not have to13. Here it does start at zero, because the break even line at €1 sits near the bottom and the distance to it is the story. The chapter on showing time covers these choices.

The focus technique is the same: grey for context, the accent for the point, and the names written at the end of each line instead of a legend.

Example: twelve months of margin per euro. First the data goes wide, one column per campaign type, with the pivot from the chapter on reshaping:

import matplotlib.dates as mdates
from matplotlib.ticker import FuncFormatter

wide = monthly.pivot(index="month", columns="campaign",
                     values="margin_per_euro")

fig_time, ax = plt.subplots()
for name in wide.columns:
    is_focus = name == highlight
    ax.plot(wide.index, wide[name],
            color=COLOURS["accent"] if is_focus else COLOURS["context"],
            linewidth=2.5 if is_focus else 1.5,
            zorder=3 if is_focus else 2)
    # Label the end of each line instead of using a legend
    ax.annotate(f"{name}  €{wide[name].iloc[-1]:.2f}",
                xy=(wide.index[-1], wide[name].iloc[-1]),
                xytext=(6, 0), textcoords="offset points", va="center",
                color=COLOURS["accent"] if is_focus else COLOURS["text"],
                fontsize=10)

ax.axhline(1, color=COLOURS["reference"], linewidth=1, linestyle=(0, (4, 3)))
ax.set_ylim(0, 5.5)
ax.set_title("Paid social prospecting has been below break even\n"
             "every month since February")
ax.set_ylabel("Gross margin per €1 of ad spend")
ax.xaxis.set_major_locator(mdates.MonthLocator(bymonth=[1, 4, 7, 10]))
ax.xaxis.set_major_formatter(mdates.DateFormatter("%b\n%Y"))
ax.yaxis.set_major_formatter(FuncFormatter(lambda v, _: f"€{v:.0f}"))

print(wide[highlight].round(2).tolist())
# [1.15, 1.1, 1.1, 1.09, 0.96, 0.89, 0.92, 0.87, 0.81, 0.81, 0.77, 0.69]

zorder draws the highlighted line on top of the grey ones where they cross. MonthLocator puts a tick at the start of each quarter, and DateFormatter("%b\n%Y") writes the month over the year. The printed values confirm the title before it goes out: 1.09 in January, 0.96 in February, below 1 every month after. If the sentence and the numbers ever disagree, the code shows it.

Line chart of gross margin per euro of ad spend by month, October 2024 to September 2025, at Ardmore Home. Paid search brand stays between €4.57 and €5.07. Paid social retargeting stays between €2.15 and €2.45. Paid search generic stays between €1.70 and €1.88. Paid social prospecting falls from €1.15 in October 2024 to €0.69 in September 2025 and has been below the break even of €1 every month since February 2025. Tap or click to enlarge

seaborn for the statistical view

Bars and lines show one number per group. Sometimes the question is about the spread: are paid social orders smaller, or is the average dragged down by a few tiny ones? That needs the whole distribution, one panel per channel, on the same scale. This is the job seaborn is built for4.

seaborn has two kinds of function, and knowing which one you are calling saves a lot of puzzlement14. Axes level functions, such as sns.histplot, sns.boxplot or sns.scatterplot, draw into one matplotlib Axes, which you can pass in with ax=. They behave like any other matplotlib call. Figure level functions, such as sns.displot, sns.relplot and sns.catplot, create and manage a whole figure of panels themselves and return a seaborn FacetGrid. They are the quick route to small multiples, with one panel per value of a column, but they handle the figure's size and layout their own way.

That second point has a practical consequence with the house style above. Ardmore's style switches on matplotlib's constrained layout, and a FacetGrid arranges its panels with matplotlib's older tight layout. The two disagree, matplotlib prints a warning, and the overall title can land on top of the panel titles. The fix is to switch constrained layout off for that one chart with plt.rc_context.

Example: order values by channel, July to September. The 12,000 orders of the quarter are generated with a right skewed distribution, the usual shape of order values, so that the overall mean comes out at Ardmore's €66:

import seaborn as sns

channels = ["Organic search", "Paid search", "Paid social",
            "Email", "Direct", "Referral"]
medians = [55, 58.5, 46.5, 65, 61.5, 53.5]   # typical order value per channel
counts = [3400, 2900, 1500, 1800, 1700, 700]

orders = pd.DataFrame({
    "channel": np.repeat(channels, counts),
    "order_value": np.concatenate([
        rng.lognormal(np.log(m), 0.55, n) for m, n in zip(medians, counts)]),
})
print(len(orders), round(orders["order_value"].mean(), 2))
# 12000 65.91
print(orders.groupby("channel")["order_value"].median().round(1))
# Direct 60.8, Email 64.7, Organic search 53.9,
# Paid search 58.0, Paid social 46.4, Referral 59.2

Then one histogram per channel, all on the same axes so they can be compared, with the median marked in the accent colour:

with plt.rc_context({"figure.constrained_layout.use": False}):
    g = sns.displot(data=orders, x="order_value", col="channel", col_wrap=3,
                    binwidth=10, height=2.2, aspect=1.3,
                    color=COLOURS["context"], edgecolor="white")
    g.set(xlim=(0, 280))
    g.set_titles("{col_name}")
    g.set_axis_labels("Order value (€)", "Orders")
    for ax, (name, group) in zip(g.axes.flat,
                                 orders.groupby("channel", sort=False)):
        median = group["order_value"].median()
        ax.axvline(median, color=COLOURS["accent"], linewidth=2)
        ax.text(median + 5, ax.get_ylim()[1] * 0.85, f"median €{median:.0f}",
                color=COLOURS["accent"], fontsize=9)
    g.figure.suptitle("Paid social orders are smaller: "
                      "median €46, elsewhere €54 to €65",
                      x=0.02, ha="left", fontweight="bold")
    g.figure.subplots_adjust(top=0.86)

The marked value is the median, not the mean. Order values are skewed to the right, so a handful of large orders pull the mean up (to €66 overall against a median of €57), and the median describes the typical order better (Foundations: median and mode). The panels share their y axis because displot shares axes by default, which is the honest choice: Referral's short bars are short because it has 700 orders, not because of how the chart was drawn. The chapter on distributions explains why one histogram per group beats one chart with six overlapping ones.

The chart adds a second fact to Darragh's story. Paid social not only costs more per euro of margin, it also brings smaller baskets. Whether that is the campaign or the products it advertises is a question for the next step of the analysis, not for the chart.

Plotly for exploring, not for the board pack

Everything so far is a static picture, and static is right for a decision. But before Darragh knew that February was the month things turned, he had to find it, and for finding things an interactive chart is quicker. Hover over a point and see the spend and revenue behind it. Click a campaign in the legend to hide it. Drag to zoom into a few months.

Plotly Express, the short interface of Plotly, makes such a chart from a tidy DataFrame in one call. It is saved as an HTML file that opens in any browser. One option decides the size of that file5. By default the whole Plotly JavaScript library is written into the file, which makes it several megabytes. With include_plotlyjs="cdn" the file loads the library from the internet instead and stays small, at the cost of needing a connection to open it.

Example: an exploration page for Darragh.

import plotly.express as px

fig = px.line(
    monthly, x="month", y="margin_per_euro", color="campaign",
    hover_data={"spend": ":,.0f", "revenue": ":,.0f",
                "margin_per_euro": ":.2f"},
    labels={"margin_per_euro": "Margin per €1", "month": "",
            "campaign": "Campaign type", "spend": "Spend (€)",
            "revenue": "Revenue (€)"},
    title="Margin per €1 of ad spend by campaign type, monthly",
    template="simple_white",
    color_discrete_sequence=["#0072B2", "#009E73", "#D55E00", "#CC79A7"],
)
fig.add_hline(y=1, line_dash="dash", line_color="#595959",
              annotation_text="Break even",
              annotation_position="bottom right")
fig.update_yaxes(rangemode="tozero")
fig.update_layout(hovermode="x unified")

fig.write_html("ardmore_explore.html", include_plotlyjs="cdn")
fig.write_html("ardmore_explore_offline.html")
# ardmore_explore.html          about 15 KB
# ardmore_explore_offline.html  about 4.8 MB

hover_data decides what appears when the pointer rests on a month, with a format for each number. hovermode="x unified" shows all four campaign types for that month in one box, which is exactly what you want when you are hunting for the month one line parted from the others. template="simple_white" starts from Plotly's plainest built in look. Plotly keeps its styles in templates, which play the same role as a matplotlib style sheet15.

Notice the title. It is a topic, not a sentence, and here that is correct. An exploration chart does not know the answer yet. Once it has helped Darragh find the answer, the answer goes into a static chart with a sentence for a title, and that chart is what Áine sees.

Plotly can also save a PNG or SVG with fig.write_image, but since Kaleido 1.0, the package that does this, it needs Chrome or Chromium installed on the machine, which Plotly can fetch for you with the plotly_get_chrome command16. For static files that a business sends around, I find it simpler to keep the finished chart in matplotlib and keep Plotly for the screen.

Saving at the right size: SVG and PNG

A chart can be perfect in the notebook and still arrive too small to read, blurry, or so large that its text looks like a footnote. The cause is almost always a confusion between inches, dots per inch and pixels. Matplotlib measures the figure in inches and the text in points, and only turns them into pixels when it saves.

The relationship is simple (Foundations: ratios and rates):

P=w×dP = w \times d

where PP is the width in pixels, ww is the figure width in inches and dd is the resolution in dots per inch. Text works the same way: a font of ff points is f/72f / 72 inches tall, so it is f×d/72f \times d / 72 pixels tall in the saved file.

Here is the rule that falls out of it, and the reason for the pairing in Ardmore's style sheet. Set the screen resolution to 100 dots per inch and make the figure width in inches one hundredth of the width at which the chart will be shown. A chart shown 700 pixels wide gets figsize 7 inches wide. Then a 12 point font is 12×100/72=16.712 \times 100 / 72 = 16.7 pixels, which is body text size on a screen, and the chart's text matches the text of the page around it. Save the PNG at 200 dots per inch and it has twice as many pixels, 1,400 by 840, so it stays sharp on high resolution screens while the browser shows it at 700 by 420 and the text at the same 16.7 pixels.

Two more details decide whether the file is useful.

  • SVG for anything that will be shown on screen and can take it, such as a web page or a document that supports vector images. It is sharp at any size, small (the finished chart above is about 8 KB) and, with svg.fonttype: none, its text stays text. PNG for email, slides and anywhere SVG is not supported, at twice the display size.
  • Avoid bbox_inches="tight" when the size matters. It crops the saved image to its content, which is convenient but changes the pixel size by an unpredictable amount. A 6 by 3.5 inch figure at 200 dots per inch, saved with the tight setting, came out at 1,223 by 723 pixels instead of 1,200 by 700 in the test for this chapter. Constrained layout keeps everything inside the canvas without changing its size.

Example: saving Ardmore's chart for the monthly report. The report is an HTML email with a 700 pixel column, plus an SVG for the shared drive:

fig_paid.savefig("ardmore_paid_return.svg", metadata={
    "Title": "Paid social prospecting returns 76c per €1",
    "Description": "Gross margin per €1 of ad spend, July to September 2025: "
                   "paid search brand €4.86, paid social retargeting €2.27, "
                   "paid search generic €1.79, paid social prospecting €0.76.",
})
fig_paid.savefig("ardmore_paid_return.png")  # 200 dpi from the style sheet

from PIL import Image
print(Image.open("ardmore_paid_return.png").size)
# (1400, 840)

The metadata dictionary writes a title and a description into the SVG file, which keeps the chart's meaning with the file wherever it is copied17. It does not replace alternative text: when the chart goes into a web page or an email, the description goes into the image's alt text as well, with the key numbers in it. Pillow, the imaging library used for the check, is installed alongside matplotlib.

Notice that the code saves fig_paid, the name given to the Figure when it was created, even though two more charts have been drawn since. That is the explicit style paying off: nothing depends on which chart happens to be the latest one.

A preflight check before a chart leaves the notebook

Style sheets remove the repeated decisions. A checklist catches the rest. The chart style guide chapter gives a checklist for people. In Python, part of it can be a function that inspects a finished Figure and lists what a reader would notice. It does not make a chart good. It stops a chart going out with a missing title, a pale colour or a bar axis that does not start at zero.

Matplotlib makes this possible because a Figure is made of objects you can ask questions of: the title of each Axes, its legend, its bars (stored as rectangle "patches"), its axis limits, its text and their font sizes.

Example: Ardmore's preflight function.

from matplotlib.colors import to_hex

def preflight(fig, min_font=9, min_contrast=3.0):
    """List the problems a reader would notice, before anyone sees the chart."""
    problems = []
    for ax in fig.axes:
        title = ax.get_title(loc="left") or ax.get_title()
        if len(title.split()) < 4:
            problems.append("title missing or names a topic: write the finding")
        if ax.get_legend() is not None:
            problems.append("legend: label the data directly instead")
        bars = ax.patches
        if bars:
            horizontal = all(p.get_x() == 0 for p in bars)
            start = ax.get_xlim()[0] if horizontal else ax.get_ylim()[0]
            if start > 0:
                problems.append("the bar axis does not start at zero")
            palest = min(bars, key=lambda p: contrast(to_hex(p.get_facecolor())))
            ratio = contrast(to_hex(palest.get_facecolor()))
            if ratio < min_contrast:
                problems.append(f"bar colour {to_hex(palest.get_facecolor())} "
                                f"has only {ratio:.1f}:1 contrast")
        ticks = ax.get_xticklabels() + ax.get_yticklabels()
        if any(t.get_text() and t.get_rotation() != 0 for t in ticks):
            problems.append("rotated labels: turn the bars horizontal")
        small = [t for t in ax.texts + ticks
                 if t.get_text() and t.get_visible() and t.get_fontsize() < min_font]
        if small:
            problems.append(f"{len(small)} text items smaller than {min_font} pt")
    return problems or ["no problems found"]

Run against the two versions of the chart:

print(preflight(fig_paid))  # the finished chart
# ['no problems found']

with plt.style.context("default"):
    default_ax = q3[["spend", "revenue"]].plot.bar()
    for problem in preflight(default_ax.figure):
        print(problem)
# title missing or names a topic: write the finding
# legend: label the data directly instead
# bar colour #ff7f0e has only 2.5:1 contrast
# rotated labels: turn the bars horizontal

The four problems it finds in the default are four of the seven listed earlier. The other three (the wrong measure, the alphabetical order, the missing source) need a person, because they depend on the question. That split is the honest scope of automation in charting: code can enforce the rules, but only someone who knows the question can choose the measure. In the last chapter of this series, on a reproducible analysis workflow, a function like this becomes a test that runs every time the report is built.

What has changed since the book

McKinney's chapter 9 is a good companion to this one, and its code still runs on the versions used here. It already uses the explicit fig, ax = plt.subplots() style, seaborn's histplot and set_style, and the pandas plotting methods shown above1. One instruction has aged. The book suggests running %matplotlib notebook to get interactive charts in Jupyter. That backend belongs to the classic notebook interface. In JupyterLab, charts appear inline without any command, and for interactive matplotlib charts the matplotlib documentation now points to the separately installed ipympl package and %matplotlib widget18. For exploring, Plotly does the same job with less setup, which is why it has its own section here.

My view

My view is that most of the effort in business charting goes into the wrong place. People spend an hour choosing a colour for one chart and no time writing the sentence it is supposed to prove. Flip it. Write the sentence first, put the decisions that never change into a style sheet once, and keep the per chart work to the few edits that serve the sentence: the measure, the order, the one highlight, the labels, the source line.

On libraries, I would learn matplotlib's explicit style properly before anything else, because pandas and seaborn both hand you matplotlib objects, and every finished chart ends up being adjusted with them. Use seaborn when the question is about distributions or many groups, and finish its output with matplotlib. Use Plotly to explore on screen, and do not let an exploration chart become the decision chart just because it is already open in a tab.

And treat the source line under the chart as part of the chart. In marketing data, "revenue" without a source is not a number, it is three numbers that disagree. A chart that says which one it shows is more honest than one that looks cleaner.

Turning analysis like this into charts and dashboards a business actually reads is a core part of my Data Science work. The code, the style sheet and the data stay with the client.

Conclusion

Charts in Python are not hard to make. They are hard to make readable, and readability comes from decisions, not from the library. The decisions that never change go into a style sheet once: the size, the fonts, the borders, the Okabe and Ito colours, text that stays text in SVG. The decisions that serve one chart come from its sentence: show the measure in the sentence, sort by it, grey for context and one colour for the point, numbers on the bars, a reference line, a source line. A short preflight function catches what slips through.

Built that way, Ardmore's chart takes Áine five seconds: paid social prospecting returns 76c of margin per €1, every other paid campaign pays back, and it has been below break even since February. The next chapter, on statistical models with statsmodels and scikit learn, asks the question the chart cannot answer by itself: how sure can Darragh be that the difference is real?

If your reports are full of default charts and nobody reads past the first page, book the free workshop: we turn one of your real questions into a chart and a house style your business can reuse, and the first two weeks of work are on me.

Sources

  1. 1.

    Wes McKinney, Python for Data Analysis: Data Wrangling with pandas, NumPy, and Jupyter, 3rd edition, O'Reilly, 2022, chapter 9, Plotting and Visualization, free online edition, https://wesmckinney.com/book/plotting-and-visualization.html

  2. 2.

    John D. Hunter, Matplotlib: A 2D Graphics Environment, Computing in Science and Engineering 9 (3), 2007, pages 90 to 95, https://doi.org/10.1109/MCSE.2007.55

  3. 3.

    pandas development team, Chart visualization, pandas 2.3 user guide, https://pandas.pydata.org/pandas-docs/version/2.3/user_guide/visualization.html

  4. 4.

    Michael L. Waskom, seaborn: statistical data visualization, Journal of Open Source Software 6 (60), 3021, 2021, https://doi.org/10.21105/joss.03021

  5. 5.

    Plotly, Interactive HTML export in Python, Plotly Python documentation, https://plotly.com/python/interactive-html-export/

  6. 6.

    Python Package Index, release histories: matplotlib 3.10.6 (30 August 2025), https://pypi.org/project/matplotlib/#history, pandas 2.3.3 (29 September 2025), https://pypi.org/project/pandas/#history, seaborn 0.13.2 (25 January 2024), https://pypi.org/project/seaborn/#history, plotly 6.3.1 (2 October 2025), https://pypi.org/project/plotly/#history, and NumPy 2.3.3 (9 September 2025), https://pypi.org/project/numpy/#history

  7. 7.

    Python Software Foundation, Python 3.14.0, released 7 October 2025, https://www.python.org/downloads/release/python-3140/

  8. 8.

    Matplotlib development team, Quick start guide: parts of a Figure, and the explicit and the implicit interfaces, Matplotlib 3.10.6 documentation, https://matplotlib.org/3.10.6/users/explain/quick_start.html

  9. 9.

    Matplotlib development team, Customizing Matplotlib with style sheets and rcParams, including the svg.fonttype setting in the default matplotlibrc file, Matplotlib 3.10.6 documentation, https://matplotlib.org/3.10.6/users/explain/customizing.html

  10. 10.

    Masataka Okabe and Kei Ito, Color Universal Design (CUD): How to make figures and presentations that are friendly to Colorblind people, jfly, 2002, revised 2008, https://jfly.uni-koeln.de/color/

  11. 11.

    W3C, Web Content Accessibility Guidelines (WCAG) 2.2, W3C Recommendation, 12 December 2024, success criteria 1.4.3 Contrast (Minimum) and 1.4.11 Non text Contrast, and the definitions of contrast ratio and relative luminance, https://www.w3.org/TR/WCAG22/

  12. 12.

    Matplotlib development team, matplotlib.axes.Axes.bar_label, Matplotlib 3.10.6 documentation, https://matplotlib.org/3.10.6/api/_as_gen/matplotlib.axes.Axes.bar_label.html

  13. 13.

    Claus O. Wilke, Fundamentals of Data Visualization, O'Reilly, 2019, chapter 6, Visualizing amounts, section 6.3 Dot plots and heatmaps, free online edition, https://clauswilke.com/dataviz/visualizing-amounts.html

  14. 14.

    Michael Waskom, Overview of seaborn plotting functions: figure level and axes level functions, seaborn 0.13.2 documentation, https://seaborn.pydata.org/tutorial/function_overview.html

  15. 15.

    Plotly, Theming and templates in Python, Plotly Python documentation, https://plotly.com/python/templates/

  16. 16.

    Plotly, Static image export in Python: Kaleido and Chrome, Plotly Python documentation, https://plotly.com/python/static-image-export/

  17. 17.

    Matplotlib development team, matplotlib.figure.Figure.savefig, Matplotlib 3.10.6 documentation, https://matplotlib.org/3.10.6/api/_as_gen/matplotlib.figure.Figure.savefig.html

  18. 18.

    Matplotlib development team, Interactive figures: Jupyter Notebooks and JupyterLab, Matplotlib 3.10.6 documentation, https://matplotlib.org/3.10.6/users/explain/figure/interactive.html

Shelter

I’m running the London Marathon for Shelter. Sunday 25 April 2027

My personal fundraiser. Shelter, the National Campaign for Homeless People Limited, registered charity 263710 (England and Wales) and SC002327 (Scotland), registered with the Fundraising Regulator.

Donate to Shelter