Scales, axes and nice ticks

Intermediate

Introduction

Every chart has to answer a practical question before it can draw anything: where on the page does the value 37.4 go? The answer is a scale, a function from data values to positions. The axis is the scale made visible, with ticks that let the reader translate positions back into values. Good ticks are round numbers, and finding them is a small, classic algorithm.

How it works

A linear scale maps a domain of data values, say 0 to 100, to a range of positions, say 0 to 400 pixels:

def scale(v):
    return r0 + (v - d0) / (d1 - d0) * (r1 - r0)

The fraction (v - d0) / (d1 - d0) says how far along the domain the value is, from 0 to 1, and the range turns that fraction into a position. Screens count y from the top down, so a vertical axis usually maps 0 to the bottom by flipping the range: (300, 0) instead of (0, 300). Values outside the domain can be clamped to its ends so that they stay inside the chart.

Ticks should be easy to read, which means a step of 1, 2 or 5 times a power of ten: 0, 20, 40 is fine, 0, 23.5, 47 is not. Paul Heckbert's "nice numbers" algorithm does this: round the data's span up to a nice number, divide by one less than the number of ticks you want, round that to a nice number for the step, then extend the axis down and up to whole steps. For data from 3 to 97 with about five ticks, the span 94 rounds to 100, the step 25 rounds to 20, and the axis runs 0, 20, 40, 60, 80, 100.

Some rules keep axes honest. A bar chart must start at zero, because the reader compares bar lengths; cutting the axis at 50 makes a bar of 60 look twice as long as one of 55. A line chart may start elsewhere, because it shows change, not size, but it should say so clearly.

When values span several powers of ten, such as city populations or prices from 1 to 10,000, a linear scale squashes the small values into a corner. A logarithmic scale spaces 1, 10, 100 and 1000 evenly, so equal distances mean equal ratios. It cannot show zero or negative values, and readers need the axis labelled clearly.

In Matplotlib, ax.set_ylim(0, 100) sets the domain, ax.set_yscale("log") switches to a log scale, and matplotlib.ticker.MaxNLocator chooses nice ticks much like the algorithm here.

Example

# Scales map data values to positions; "nice" tick values make axes easy to read.
import math


def nice(x, round_it):
    """A number near x that is 1, 2 or 5 times a power of ten."""
    exp = math.floor(round(math.log10(x), 12))
    f = x / 10**exp
    if round_it:
        n = 1 if f < 1.5 else 2 if f < 3 else 5 if f < 7 else 10
    else:
        n = 1 if f <= 1 else 2 if f <= 2 else 5 if f <= 5 else 10
    return n * 10**exp


def ticks(lo, hi, count=5):
    step = nice(nice(hi - lo, False) / (count - 1), True)
    start = math.floor(lo / step) * step
    end = math.ceil(hi / step) * step
    return [round(start + i * step, 10) for i in range(round((end - start) / step) + 1)]


def scale(domain, out):
    (d0, d1), (r0, r1) = domain, out
    return lambda v: r0 + (v - d0) / (d1 - d0) * (r1 - r0)


for lo, hi in ((3, 97), (0.13, 0.87), (1200, 4750)):
    print(f"data {lo} to {hi}: ticks", " ".join(f"{t:g}" for t in ticks(lo, hi)))

y = scale((0, 100), (300, 0))  # screen y grows downwards, so 0 maps to the bottom
print("y positions:", [y(v) for v in (0, 25, 50, 100)])
Open in compiler

Line by line

  1. nice finds a 1, 2 or 5 times a power of ten near x, rounding to the nearest or upwards.
  2. ticks computes the step from the span and the wanted number of ticks, then runs from a whole step below the data to a whole step above.
  3. round(..., 10) removes the tiny errors floating-point arithmetic leaves, such as 0.6000000000000001.
  4. scale returns a function; with the range (300, 0) the value 0 lands at the bottom, y = 300.

Expected result

data 3 to 97: ticks 0 20 40 60 80 100
data 0.13 to 0.87: ticks 0 0.2 0.4 0.6 0.8 1
data 1200 to 4750: ticks 1000 2000 3000 4000 5000
y positions: [300.0, 225.0, 150.0, 0.0]

In the real world

Every charting library contains a tick algorithm: Matplotlib's locators, D3's scale.ticks() and spreadsheet charts all choose 1-2-5 steps. Scientific papers plot earthquakes, incomes and virus counts on log scales, and financial charts often show prices on a log scale so that a 10% rise looks the same at any price level.

Common mistakes

  • Starting a bar chart's axis above zero, which exaggerates differences.
  • Tick values like 23.7 and 47.4, which readers cannot use to estimate values.
  • Forgetting that screen y grows downwards, which draws charts upside down.
  • Plotting zero or negative values on a log scale, where they have no position.

Best practices

  • Use a library's tick algorithm, or the nice-numbers rule, rather than dividing the range evenly.
  • Start bars at zero, and label any axis that does not.
  • Use a log scale when the largest value is more than about 100 times the smallest, and say so on the axis.

Summary

A scale maps a data domain to a range of positions with one line of arithmetic, flipped for screen y. Axes use nice tick steps of 1, 2 or 5 times a power of ten, computed from the data's span. Bars start at zero, and log scales show data that spans many orders of magnitude.

Quick check

1. A scale maps 0..100 to 0..400. Where does 25 go?
2. Which tick sequence is 'nice'?
3. Why must a bar chart's axis start at zero?
4. When is a logarithmic scale a good choice?

Key takeaways

  • A linear scale is r0 + (v - d0) / (d1 - d0) × (r1 - r0); flip the range for screen coordinates.
  • Tick steps of 1, 2 or 5 times a power of ten are easiest to read.
  • Bars must start at zero; use a log scale when values span several powers of ten.

Practice problems for this lesson

My notes

Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.