Selecting colours and line styles for figures with several curves#

← Previous | Oldest ↻
December 05, 2026 () by Anders Lervik | Category: visualisation
Tagged: jupyter | matplotlib | python | visualisation

Introduction#

In the post on polyprotic acids, I drew the fractions of four species in the same figure, and had trouble telling the curves apart with colours alone. I ended up selecting dash patterns by hand. For colours, there are palettes that are designed from measurements of how we see colours. In this post, I look at how line styles are selected in some plotting tools, and try to select colours and line styles in a more systematic way:

The fractions of the phosphate species with the previous and the new colours

The figure shows the fractions of the species of phosphoric acid (\(\text{H}_3\text{PO}_4\)), with the colours of that post to the left and the new colours to the right. The dash patterns are the same in the two panels, and they are the ones I selected by hand. To me, the colours to the right are a bit easier to distinguish.

The advice in the literature on graphs is fairly consistent. Cleveland [1] recommends solid lines as long as the curves can be told apart, then dashed and dotted lines, and finally to place the curves in separate panels. Tufte [2] prefers to write the name of each curve next to the curve, so that no legend is needed. He also points out that two marks next to each other create a third visual element, the space between them [3], and a dashed line has many such spaces. Wilke [4] advises against dashed lines, since matching the patterns to a legend takes effort.

There are few measurements to build on. Schutz [5] compared 25 line styles in 1961, and found that dashed and dotted lines were often mixed up, with each other and with the solid line. Sterzik et al. [6] have measured how small a difference in dashing we can see, and I use their results below. For the colours, I follow the approach of Petroff [7].

We begin by constructing some test cases, which are figures with four curves each. Four is the number of curves in the figure above, and Wilke [4] gives three to five as the number of categories that colours work best for. It is also the number of line styles that matplotlib has names for (solid, dashed, dash-dotted and dotted). Figures with six curves are considered at the end of the section on dash patterns.

After having made the test cases, we consider the colours and calculate how far apart they are, also with simulated colour-vision deficiency and in grey scale. We then search for colours that are far apart in all of these views, to find a possible colour scheme. Next, we look at the line styles of some plotting tools, and try to do the same for dash patterns, with a distance between patterns and a search. For figures in black and white, the dash patterns can be combined with shades of grey. The last section, Using the colours and the line styles, shows how the colours and the line styles can be used in other figures with matplotlib.

Test cases#

https://mybinder.org/badge_logo.svg

We start by importing numpy and scipy (for the numerics), and matplotlib and seaborn (for the plotting):

[1]:
import itertools

import numpy as np
import seaborn as sns
from matplotlib import colormaps, style
from matplotlib import pyplot as plt
from matplotlib.colors import to_hex, to_rgb
from scipy.special import jv
from scipy.stats import wasserstein_distance

sns.set_theme(style="ticks", context="notebook", palette="colorblind")
%matplotlib inline

LINE_WIDTH = 2.0  # The line width (in points) used for the figures.

To compare colours and line styles, we need some figures to try them on. I have selected four cases with four curves each, where the curves meet in different ways:

  • The Bessel functions \(J_0\) to \(J_3\), which cross each other many times.

  • The concentrations for the consecutive reactions \(\text{A} \to \text{B} \to \text{C} \to \text{D}\). Each curve crosses its neighbours, and two of them end up close to zero.

  • Van der Waals isotherms around the critical temperature, which run side by side without crossing.

  • The fractions of the phosphate species as a function of the pH, from the post on polyprotic acids. The curves have steep parts, and three of them are close to zero for most of the pH range.

Each function below returns the values for the horizontal axis, the curves, and labels for the two axes:

[2]:
def bessel():
    """The Bessel functions of the first kind of order 0 to 3."""
    x = np.linspace(0, 15, 600)
    curves = {f"$J_{n}$": jv(n, x) for n in range(4)}
    return x, curves, "$x$", "$J_n(x)$"


def consecutive_reactions():
    """Concentrations for the first-order reactions A → B → C → D."""
    time = np.linspace(0, 12, 500)
    k1, k2, k3 = 1.0, 0.5, 0.25
    a = np.exp(-k1 * time)
    b = k1 / (k2 - k1) * (np.exp(-k1 * time) - np.exp(-k2 * time))
    c = (
        k1
        * k2
        * (
            np.exp(-k1 * time) / ((k2 - k1) * (k3 - k1))
            + np.exp(-k2 * time) / ((k1 - k2) * (k3 - k2))
            + np.exp(-k3 * time) / ((k1 - k3) * (k2 - k3))
        )
    )
    curves = {"A": a, "B": b, "C": c, "D": 1.0 - a - b - c}
    return time, curves, "Time", "Concentration"


def van_der_waals():
    """Van der Waals isotherms in reduced units."""
    volume = np.linspace(0.45, 3.0, 500)
    curves = {
        f"$T_r$ = {temperature}": 8.0 * temperature / (3.0 * volume - 1.0)
        - 3.0 / volume**2
        for temperature in (0.9, 1.0, 1.1, 1.2)
    }
    return volume, curves, "$V_r$", "$p_r$"


def phosphate_fractions():
    """The fractions of the phosphate species as a function of the pH."""
    pH = np.linspace(0, 14, 600)
    hydrogen = 10.0**-pH
    ratios = [np.ones_like(hydrogen)]
    for pka in (2.14, 7.20, 12.37):
        ratios.append(ratios[-1] * 10.0**-pka / hydrogen)
    fractions = np.array(ratios) / np.sum(ratios, axis=0)
    labels = ["H$_3$PO$_4$", "H$_2$PO$_4^-$", "HPO$_4^{2-}$", "PO$_4^{3-}$"]
    return pH, dict(zip(labels, fractions)), "pH", "Fraction"


CASES = {
    "Bessel functions": bessel,
    "Consecutive reactions": consecutive_reactions,
    "Van der Waals isotherms": van_der_waals,
    "Phosphate fractions": phosphate_fractions,
}

We draw the four cases with solid lines and the first four colours of the colorblind palette in seaborn:

[3]:
COLORBLIND = sns.color_palette("colorblind", 4)


def set_limits(ax, case):
    """Set the limits for the cases where part of the curves is left out."""
    if case == "Van der Waals isotherms":
        ax.set(xlim=(0.45, 3.0), ylim=(0.0, 2.5))


fig, axes = plt.subplots(
    constrained_layout=True, nrows=2, ncols=2, figsize=(10, 6)
)
for ax, (case, function) in zip(axes.flat, CASES.items()):
    x, curves, xlabel, ylabel = function()
    for colour, (label, y) in zip(COLORBLIND, curves.items()):
        ax.plot(x, y, color=colour, lw=LINE_WIDTH, label=label)
    ax.set(xlabel=xlabel, ylabel=ylabel)
    ax.set_title(case, pad=30)
    set_limits(ax, case)
    ax.legend(
        frameon=False,
        fontsize="small",
        ncols=4,
        loc="lower center",
        bbox_to_anchor=(0.5, 1.0),
        columnspacing=1.2,
        handlelength=1.8,
    )
sns.despine(fig=fig)
../../../_images/posts_2026_linestyles_linestyles_5_0.png

With colours, most of the cases are easy to read. The Bessel functions take some effort to follow after the first few crossings.

Selecting colours#

Colours are not always available. A figure can be printed in black and white, and some readers have a colour-vision deficiency (see Fundamentals of Data Visualization by Claus Wilke). The colorblind palette in seaborn, which we used above, is made with this in mind, and we can check how well it does by simulating how the colours look. For the simulation, we use the matrices of Machado et al. for the three types of dichromacy. To compare colours, we convert them to the CIELAB colour space, where the distance between two colours is closer to the difference we see than it is for the red, green and blue values.

The calculation is done in steps. The red, green and blue values of a colour on a screen (sRGB values) are not proportional to the intensity of the light, so they are first converted to values that are (linear values). The matrices for the simulation are applied to the linear values, and the linear values are also the starting point for the conversion to CIELAB. For grey scale, we replace each colour by the grey with the same luminance. The numbers and the formulas are taken from the sources given in the code:

[4]:
# The matrices of Machado et al. for the three types of dichromacy (a
# severity of 1.0), which are applied to linear RGB values. They are from
# https://www.inf.ufrgs.br/~oliveira/pubs_files/CVD_Simulation/CVD_Simulation.html
MACHADO = {
    "Protanopia": [
        [0.152286, 1.052583, -0.204868],
        [0.114503, 0.786281, 0.099216],
        [-0.003882, -0.048116, 1.051998],
    ],
    "Deuteranopia": [
        [0.367322, 0.860646, -0.227968],
        [0.280085, 0.672501, 0.047413],
        [-0.011820, 0.042940, 0.968881],
    ],
    "Tritanopia": [
        [1.255528, -0.076749, -0.178779],
        [-0.078411, 0.930809, 0.147602],
        [0.004733, 0.691367, 0.303900],
    ],
}
# The matrix that converts linear sRGB values to CIE XYZ (with D65 as the
# white point), from http://www.brucelindbloom.com/Eqn_RGB_XYZ_Matrix.html
# The second row gives the luminance (Y). WHITE is XYZ for the white point.
RGB_TO_XYZ = np.array(
    [
        [0.4124564, 0.3575761, 0.1804375],
        [0.2126729, 0.7151522, 0.0721750],
        [0.0193339, 0.1191920, 0.9503041],
    ]
)
WHITE = np.array([0.95047, 1.0, 1.08883])
VIEWS = ["Normal vision", *MACHADO, "Grey scale"]


def to_linear(rgb):
    """Convert sRGB values (0 to 1) to linear RGB values.

    The linear values are proportional to the intensity of the light.
    This is the transfer function of the sRGB standard, see
    https://en.wikipedia.org/wiki/SRGB#Transfer_function_(%22gamma%22)
    """
    rgb = np.asarray(rgb, dtype=float)
    return np.where(
        rgb <= 0.04045, rgb / 12.92, ((rgb + 0.055) / 1.055) ** 2.4
    )


def from_linear(linear):
    """Convert linear RGB values to sRGB values (0 to 1).

    This is the inverse of to_linear. Values outside the range from
    0 to 1 can not be shown on a screen, and are moved to the limits.
    """
    linear = np.clip(linear, 0.0, 1.0)
    return np.where(
        linear <= 0.0031308,
        12.92 * linear,
        1.055 * linear ** (1.0 / 2.4) - 0.055,
    )


def to_lab(rgb):
    """Convert sRGB values (0 to 1) to CIELAB.

    The colours are converted to linear values, then to CIE XYZ, and
    then to CIELAB with the formulas in
    https://en.wikipedia.org/wiki/CIELAB_color_space#From_CIE_XYZ_to_CIELAB

    Returns:
        The lightness (L*, from 0 for black to 100 for white), and the
        positions on the green-red axis (a*) and the blue-yellow axis (b*).
    """
    ratio = to_linear(rgb) @ RGB_TO_XYZ.T / WHITE
    delta = 6.0 / 29.0
    f = np.where(
        ratio > delta**3, np.cbrt(ratio), ratio / (3.0 * delta**2) + 4.0 / 29.0
    )
    return np.stack(
        [
            116.0 * f[..., 1] - 16.0,
            500.0 * (f[..., 0] - f[..., 1]),
            200.0 * (f[..., 1] - f[..., 2]),
        ],
        axis=-1,
    )


def simulate(rgb, view):
    """Simulate how sRGB colours look in a given view.

    For a colour-vision deficiency, the matrix of Machado et al. is
    applied to the linear values of the colour. For grey scale, the
    colour is replaced by the grey with the same luminance.

    Args:
        rgb: The sRGB colours (values from 0 to 1).
        view: "Normal vision", "Grey scale" or one of the keys
            in MACHADO.

    Returns:
        The sRGB colours as they look in the view.
    """
    rgb = np.asarray(rgb, dtype=float)
    if view == "Normal vision":
        return rgb
    if view == "Grey scale":
        # A grey with the same luminance (the Y in XYZ) as the colour:
        luminance = to_linear(rgb) @ RGB_TO_XYZ[1]
        return from_linear(np.stack([luminance] * 3, axis=-1))
    return from_linear(to_linear(rgb) @ np.array(MACHADO[view]).T)


def closest_colours(colours, view):
    """Return the smallest distance between colours in a view, and the pair."""
    lab = to_lab(simulate(np.array(colours), view))
    pairs = itertools.combinations(range(len(colours)), 2)
    return min((np.linalg.norm(lab[i] - lab[j]), i, j) for i, j in pairs)


names = ["blue", "orange", "green", "red"]
print(f"{'View':14s} {'Closest pair of colours':>26s}")
for view in VIEWS:
    smallest, i, j = closest_colours(COLORBLIND, view)
    print(f"{view:14s} {smallest:8.1f} ({names[i]} and {names[j]})")
lightness = to_lab(np.array(COLORBLIND))[:, 0]
text = ", ".join(f"{i} {j:.0f}" for i, j in zip(names, lightness))
print(f"\nLightness: {text}")
View              Closest pair of colours
Normal vision      25.6 (orange and red)
Protanopia         18.5 (orange and red)
Deuteranopia       12.6 (orange and red)
Tritanopia         16.6 (blue and green)
Grey scale          3.6 (green and red)

Lightness: blue 46, orange 66, green 58, red 54

For two patches of colour next to each other, a distance of about 2.3 is often given as the smallest difference we can notice (see colour difference). Thin lines that are matched to a legend need a larger distance, and I have not found a number for how large. We therefore use the distances to compare palettes with each other. For the colorblind palette, the closest colours are 13 to 19 apart with a colour-vision deficiency, against 26 with normal vision. In grey scale, two of the colours (green and red) are only 3.6 apart, and end up as nearly the same grey.

To see what this means for a figure, we draw two of the cases, store the figure as an image, and apply the simulation to the image:

[5]:
def draw_curves(ax, case, patterns, cap, colours=None):
    """Draw the curves for a case with the given dash patterns.

    Args:
        ax: The axes to draw in.
        case: The name of the case (a key in CASES).
        patterns: A dash pattern for each curve.
        cap: The shape of the line ends ("butt" or "round").
        colours: A colour for each curve. The default is black.
    """
    x, curves, xlabel, ylabel = CASES[case]()
    for i, (y, pattern) in enumerate(zip(curves.values(), patterns)):
        ax.plot(
            x,
            y,
            color="k" if colours is None else colours[i],
            lw=LINE_WIDTH,
            dashes=pattern,
            dash_capstyle=cap,
        )
    set_limits(ax, case)
    return xlabel, ylabel


def draw_solid(cases, colours):
    """Draw cases next to each other with solid lines."""
    fig, axes = plt.subplots(
        constrained_layout=True,
        ncols=len(cases),
        figsize=(4 * len(cases), 2.6),
    )
    for ax, case in zip(axes, cases):
        xlabel, ylabel = draw_curves(ax, case, [()] * 4, "butt", colours)
        ax.set(xlabel=xlabel, ylabel=ylabel)
    sns.despine(fig=fig)
    return fig


def show_views(figure, views):
    """Show how a figure looks in different views."""
    figure.canvas.draw()
    image = np.asarray(figure.canvas.buffer_rgba())[..., :3] / 255.0
    plt.close(figure)
    width, height = figure.get_size_inches()
    fig, axes = plt.subplots(
        constrained_layout=True,
        nrows=len(views),
        figsize=(width, (height + 0.4) * len(views)),
    )
    for ax, view in zip(axes, views):
        ax.imshow(simulate(image, view))
        ax.set_title(view, loc="left", fontsize=11)
        ax.set_axis_off()


TWO_CASES = ["Phosphate fractions", "Consecutive reactions"]
THREE_VIEWS = ["Normal vision", "Deuteranopia", "Grey scale"]
show_views(draw_solid(TWO_CASES, COLORBLIND), THREE_VIEWS)
../../../_images/posts_2026_linestyles_linestyles_10_0.png

With deuteranopia (the most common type of colour-vision deficiency), the four curves can still be told apart. In grey scale, two of them can not.

The lightness of the colours is what matters in grey scale, and we can check if other palettes do better. For each palette, we use the first four colours and find the distance between the two closest colours in each of the five views. The Okabe-Ito palette has eight colours, and for this palette we also find the four colours that are furthest apart. The last row is four colours taken from the viridis colour map, which goes from dark to light:

[6]:
def style_colours(name, number=4):
    """Return the first colours of a matplotlib style."""
    colours = style.library[name]["axes.prop_cycle"].by_key()["color"]
    return [to_rgb(colour) for colour in colours[:number]]


def smallest_distance(colours):
    """Return the smallest distance between colours over all the views."""
    return min(closest_colours(colours, view)[0] for view in VIEWS)


OKABE_ITO = [
    to_rgb(colour)
    for colour in (
        "#E69F00",
        "#56B4E9",
        "#009E73",
        "#F0E442",
        "#0072B2",
        "#D55E00",
        "#CC79A7",
        "#000000",
    )
]
best_four = max(itertools.combinations(OKABE_ITO, 4), key=smallest_distance)
viridis = [colormaps["viridis"](i)[:3] for i in np.linspace(0.0, 0.8, 4)]
PALETTES = {
    "seaborn colorblind": COLORBLIND,
    "seaborn deep": sns.color_palette("deep", 4),
    "matplotlib tab10": sns.color_palette("tab10", 4),
    "petroff10": style_colours("petroff10"),
    "petroff6": style_colours("petroff6"),
    "Okabe-Ito": OKABE_ITO[:4],
    "Okabe-Ito (best four)": list(best_four),
    "Tol bright": [
        to_rgb(colour)
        for colour in ("#4477AA", "#EE6677", "#228833", "#CCBB44")
    ],
    "viridis (four samples)": viridis,
}

print(f"{'Palette':24s}" + "".join(f"{view:>15s}" for view in VIEWS))
for name, colours in PALETTES.items():
    distances = [closest_colours(colours, view)[0] for view in VIEWS]
    print(f"{name:24s}" + "".join(f"{i:15.1f}" for i in distances))
print("\nOkabe-Ito (best four): " + ", ".join(to_hex(i) for i in best_four))
Palette                   Normal vision     Protanopia   Deuteranopia     Tritanopia     Grey scale
seaborn colorblind                 25.6           18.5           12.6           16.6            3.6
seaborn deep                       29.7            7.3            9.6           18.9            1.3
matplotlib tab10                   40.3            4.6            7.3           17.9            1.1
petroff10                          45.1           42.4           41.2           27.6            8.0
petroff6                           48.8           36.8           31.5           33.8            6.5
Okabe-Ito                          35.1           24.7           17.0           16.1            0.8
Okabe-Ito (best four)              26.4           24.8           24.9           24.8           19.3
Tol bright                         52.2           29.8           19.1           13.1            1.1
viridis (four samples)             40.8           25.6           20.1           20.4           19.7

Okabe-Ito (best four): #56b4e9, #f0e442, #0072b2, #000000

When the first four colours are used, all the palettes with different hues lose most of the distance in grey scale. The colours by Petroff (petroff10 in matplotlib) do best. They were found by generating random sets of colours, and rejecting those where two colours were too close, in lightness or with a colour-vision deficiency.

Two of the rows keep most of the distance in grey scale. The colours from viridis mainly differ in lightness, and the best four of the Okabe-Ito colours go from black to a light yellow that is hard to see on a white background. We can use the same idea, and select colours with different hues that are spread out in lightness and not too light. Letting one of the colours be black gives a larger spread.

To find such colours, we take the colours on a grid of red, green and blue values, and sort them into groups by their hue (blue, red, yellow and blue-green). Colours that are close to grey or very light are left out. We then search for one colour from each group, so that the two closest colours are as far apart as possible when we consider all five views:

[7]:
grid = np.array(list(itertools.product(np.linspace(0, 1, 18), repeat=3)))
grid_lab = to_lab(grid)
grid_hue = np.degrees(np.arctan2(grid_lab[:, 2], grid_lab[:, 1])) % 360
grid_chroma = np.hypot(grid_lab[:, 1], grid_lab[:, 2])

# Limits for the hue (in degrees), the smallest chroma, and the lightness:
HUES = {
    "blue": (255, 300, 45, 20, 65),
    "red": (15, 45, 55, 38, 60),
    "yellow": (55, 90, 55, 58, 78),
    "blue-green": (160, 215, 30, 40, 72),
}


def distances_in_all_views(colours1, colours2, grey_weight=1.0):
    """Return the distances between colours, as the smallest over the views.

    Args:
        colours1: The first set of colours.
        colours2: The second set of colours.
        grey_weight: A factor for the distances in grey scale.
    """
    smallest = np.full((len(colours1), len(colours2)), np.inf)
    for view in VIEWS:
        lab1 = to_lab(simulate(colours1, view))
        lab2 = to_lab(simulate(colours2, view))
        difference = lab1[:, np.newaxis, :] - lab2[np.newaxis, :, :]
        factor = grey_weight if view == "Grey scale" else 1.0
        smallest = np.minimum(
            smallest, factor * np.linalg.norm(difference, axis=-1)
        )
    return smallest


def search_colours(hues, black=False, starts=20):
    """Search for one colour for each hue, as far apart as possible.

    Args:
        hues: The names of the hues to use (keys in HUES).
        black: If True, black is added as an extra colour.
        starts: The number of random starting points for the search.

    Returns:
        The colours that were found (with black as the last one).
    """
    groups = []
    for low, high, chroma, dark, light in (HUES[hue] for hue in hues):
        groups.append(
            np.flatnonzero(
                (grid_hue > low)
                & (grid_hue < high)
                & (grid_chroma > chroma)
                & (grid_lab[:, 0] > dark)
                & (grid_lab[:, 0] < light)
            )
        )
    members = np.concatenate(groups)
    position = {int(j): i for i, j in enumerate(members)}
    between = distances_in_all_views(grid[members], grid[members])
    to_black = np.full(len(members), np.inf)
    if black:
        black_colour = np.zeros((1, 3))
        to_black = distances_in_all_views(grid[members], black_colour)[:, 0]

    def score(selected):
        rows = [position[i] for i in selected]
        pairs = between[np.ix_(rows, rows)][np.triu_indices(len(rows), k=1)]
        return min(pairs.min(), to_black[rows].min())

    rng = np.random.default_rng(1)
    best = (0.0, None)
    for _ in range(starts):
        selected = [int(rng.choice(group)) for group in groups]
        improved = True
        while improved:
            improved = False
            for k, group in enumerate(groups):
                # Try all the colours in group k, with the others fixed:
                fixed = selected[:k] + selected[k + 1 :]
                others = [position[i] for i in fixed]
                rows = [position[int(i)] for i in group]
                trial = np.minimum(
                    between[np.ix_(rows, others)].min(axis=1), to_black[rows]
                )
                candidate = int(group[trial.argmax()])
                changed = selected[:k] + [candidate] + selected[k + 1 :]
                if score(changed) > score(selected) + 1.0e-9:
                    selected, improved = changed, True
        if score(selected) > best[0]:
            best = (score(selected), selected)
    colours = [tuple(grid[i]) for i in best[1]]
    return colours + [(0.0, 0.0, 0.0)] if black else colours


OPTIONS = {
    "Blue, orange, red, purple": PALETTES["petroff6"],
    "Blue, orange, red, black": PALETTES["petroff6"][:3] + [(0.0, 0.0, 0.0)],
    "Dark blue, red, yellow, black": search_colours(
        ["blue", "red", "yellow"], black=True
    ),
    "Dark blue, red, blue-green, yellow": search_colours(
        ["blue", "red", "blue-green", "yellow"]
    ),
}

print(f"{'Colours':36s}" + "".join(f"{view:>15s}" for view in VIEWS))
for name, colours in OPTIONS.items():
    distances = [closest_colours(colours, view)[0] for view in VIEWS]
    print(f"{name:36s}" + "".join(f"{i:15.1f}" for i in distances))
print()
for name, colours in OPTIONS.items():
    print(f"{name}: " + ", ".join(to_hex(colour) for colour in colours))
Colours                               Normal vision     Protanopia   Deuteranopia     Tritanopia     Grey scale
Blue, orange, red, purple                      48.8           36.8           31.5           33.8            6.5
Blue, orange, red, black                       58.0           45.9           31.5           47.2           11.2
Dark blue, red, yellow, black                  61.1           48.0           27.6           38.3           25.5
Dark blue, red, blue-green, yellow             59.7           47.5           36.8           40.5           17.9

Blue, orange, red, purple: #5790fc, #f89c20, #e42536, #964a8b
Blue, orange, red, black: #5790fc, #f89c20, #e42536, #000000
Dark blue, red, yellow, black: #002da5, #e13c3c, #f0b44b, #000000
Dark blue, red, blue-green, yellow: #002d78, #b41e00, #1e96a5, #f0b44b

The first row is the first four colours of petroff6, and in the second row the purple is replaced by black. The last two rows are from the search, with and without black. We draw two of the cases with the four sets of colours, as they are and in grey scale:

[8]:
fig, axes = plt.subplots(
    constrained_layout=True,
    nrows=4,
    ncols=len(OPTIONS),
    figsize=(3.3 * len(OPTIONS), 9.5),
    sharex="row",
    sharey="row",
)
for ax, name in zip(axes[0], OPTIONS):
    ax.set_title(name, fontsize=10)
for column, colours in enumerate(OPTIONS.values()):
    grey = simulate(np.array(colours), "Grey scale")
    for i, case in enumerate(["Phosphate fractions", "Bessel functions"]):
        above, below = axes[2 * i, column], axes[2 * i + 1, column]
        draw_curves(above, case, [()] * 4, "butt", colours)
        xlabel, ylabel = draw_curves(below, case, [()] * 4, "butt", grey)
        below.set_xlabel(xlabel)
        if column == 0:
            above.set_ylabel(ylabel)
            below.set_ylabel(ylabel)
sns.despine(fig=fig)
../../../_images/posts_2026_linestyles_linestyles_16_0.png

Which of these is the easiest to read will probably differ from person to person. I find the two sets with black the easiest to follow. Of these, I like the look of the second set best, but the curves are easier to tell apart with the third set (dark blue, red, yellow and black), and it is the one that does best in grey scale.

I will use the third set, but with a darker yellow, since the yellow from the search is hard to see against the white background. I also made the red a little darker, so that the two do not come too close in grey scale. The contrast ratio against white, from the guidelines for accessible web pages, shows the effect of the change:

[9]:
def contrast_to_white(colour):
    """Return the contrast ratio between a colour and white."""
    luminance = to_linear(np.array(colour)) @ RGB_TO_XYZ[1]
    return 1.05 / (luminance + 0.05)


searched = OPTIONS["Dark blue, red, yellow, black"]
COLOURS = [searched[0], to_rgb("#d22d3c"), to_rgb("#dc9a1e"), searched[3]]

header = "".join(f"{view:>15s}" for view in VIEWS)
print(f"{'Colours':18s}{'Contrast':>10s}{header}")
for name, colours in (
    ("From the search", searched),
    ("With the change", COLOURS),
):
    distances = [closest_colours(colours, view)[0] for view in VIEWS]
    print(
        f"{name:18s}{contrast_to_white(colours[2]):10.2f}"
        + "".join(f"{i:15.1f}" for i in distances)
    )
print("\nColours: " + ", ".join(to_hex(colour) for colour in COLOURS))
show_views(draw_solid(TWO_CASES, COLOURS), THREE_VIEWS)
Colours             Contrast  Normal vision     Protanopia   Deuteranopia     Tritanopia     Grey scale
From the search         1.85           61.1           48.0           27.6           38.3           25.5
With the change         2.42           62.8           41.8           33.3           38.3           21.3

Colours: #002da5, #d22d3c, #dc9a1e, #000000
../../../_images/posts_2026_linestyles_linestyles_18_1.png

The contrast of the yellow against white goes up, at the cost of a shorter distance between the closest colours in grey scale.

Even with colours that are selected for it, two of the curves are close in some of the views, and with more than four curves it gets harder. We need a second way of telling the curves apart, and the most common one is to use different line styles.

Line styles in plotting tools#

A dash pattern is given as a list of lengths. The first is the length of a mark, the second is the length of the gap after it, then comes the length of the next mark, and so on. In most tools, these lengths are given in units of the line width. Below are the first four line styles of some plotting tools, written in this way. The numbers are taken from the source code or the documentation of the tools:

  • matplotlib: the settings lines.dashed_pattern, lines.dashdot_pattern and lines.dotted_pattern.

  • seaborn: the patterns used for the style argument of lineplot.

  • R: the line types dashed, dotted and dotdash. R draws lines with round ends by default.

  • ggplot2: the first line types of the default scale.

  • Grace: the line styles 2, 3 and 4.

  • gnuplot: the dash types 2, 3 and 4 of the cairo terminals. The scaling of these patterns depends on more than the line width, so the numbers are approximate.

  • plotly: dot, dash and longdash. The unit is the line width, but at least 3 pixels. The numbers below are for a line that is 2 pixels wide.

  • TikZ (used by pgfplots): dashed, dotted and dash dot. The dashes and gaps are given in points and do not change with the line width. The numbers below are for a line that is 2 points wide, which is thicker than the lines normally used with TikZ.

  • Makie: :dash, :dot and :dashdot.

The last set is the one I selected by hand for the post on polyprotic acids. I call it the handplukka set, which is Norwegian for hand-picked:

[10]:
# The first four line styles of the tools. Each pattern is a tuple with
# lengths (mark, gap, mark, gap, ...) in units of the line width, and an
# empty tuple is a solid line. The last item is the shape of the line ends:
TOOLS = {
    "matplotlib": (
        [
            (),
            tuple(plt.rcParams["lines.dashed_pattern"]),
            tuple(plt.rcParams["lines.dashdot_pattern"]),
            tuple(plt.rcParams["lines.dotted_pattern"]),
        ],
        "butt",
    ),
    "seaborn": ([(), (4, 1.5), (1, 1), (3, 1.25, 1.5, 1.25)], "butt"),
    "R": ([(), (4, 4), (1, 3), (1, 3, 4, 3)], "round"),
    "ggplot2": ([(), (2, 2), (4, 2), (4, 4)], "butt"),
    "Grace": ([(), (1, 3), (5, 3), (7, 3)], "butt"),
    "gnuplot": ([(), (5, 8), (1, 4), (8, 4, 2, 4)], "butt"),
    "plotly": ([(), (1.5, 1.5), (4.5, 4.5), (7.5, 7.5)], "butt"),
    "TikZ": (
        [
            (),
            (3 / LINE_WIDTH, 3 / LINE_WIDTH),
            (1, 2 / LINE_WIDTH),
            (3 / LINE_WIDTH, 2 / LINE_WIDTH, 1, 2 / LINE_WIDTH),
        ],
        "butt",
    ),
    "Makie": ([(), (3, 3), (1, 2), (3, 3, 1, 3)], "butt"),
    "Handplukka": ([(), (5, 3), (5, 2.5, 0.01, 2.5), (0.01, 2.2)], "round"),
}

To compare the patterns, we draw them as straight lines. For each pattern, we also calculate the fraction of the line that is covered by ink, and the period (the length after which the pattern repeats). A round end adds half a line width to each end of a mark:

[11]:
def visible(pattern, cap):
    """Return the visible marks and gaps of a pattern.

    Args:
        pattern: The lengths (mark, gap, mark, gap, ...) in line widths.
        cap: The shape of the line ends ("butt" or "round").

    Returns:
        The lengths of the marks and the lengths of the gaps, as seen
        on the figure.
    """
    extra = 1.0 if cap == "round" else 0.0
    marks = [mark + extra for mark in pattern[0::2]]
    gaps = [max(gap - extra, 0.0) for gap in pattern[1::2]]
    return marks, gaps


def ink_fraction(pattern, cap):
    """Return the fraction of a line that is covered by ink."""
    if not pattern:
        return 1.0
    marks, _ = visible(pattern, cap)
    return min(sum(marks) / sum(pattern), 1.0)


def describe(pattern, cap):
    """Return a short text that describes a pattern."""
    if not pattern:
        return "solid"
    lengths = "–".join(f"{length:g}" for length in pattern)
    ink = ink_fraction(pattern, cap)
    return f"{lengths}   (ink {ink:.0%}, period {sum(pattern):g})"


fig, axes = plt.subplots(
    constrained_layout=True, nrows=5, ncols=2, figsize=(10, 7.5)
)
for ax, (tool, (patterns, cap)) in zip(axes.flat, TOOLS.items()):
    for i, pattern in enumerate(patterns):
        ax.plot(
            [0, 1],
            [-i, -i],
            color="k",
            lw=LINE_WIDTH,
            dashes=pattern,
            dash_capstyle=cap,
        )
        ax.text(1.03, -i, describe(pattern, cap), va="center", fontsize=8)
    ax.set(xlim=(0, 1.8), ylim=(-3.6, 0.6))
    ax.set_title(tool, loc="left", fontsize=11)
    ax.set_axis_off()
../../../_images/posts_2026_linestyles_linestyles_23_0.png

Most of the tools offer a dashed line, a dotted line and a line with dashes and dots among the first four. Grace and plotly have no line with dashes and dots, and ggplot2 has neither dots nor dashes with dots. The proportions are quite different. In matplotlib and seaborn, the gaps are shorter than two line widths, while gnuplot and plotly have gaps of up to eight line widths. The amount of ink also varies, from 20 % for the dotted line in gnuplot to 75 % for the dashed line in the handplukka set. For TikZ, the three patterns are almost the same at this line width.

I have not found any reason given for these choices in the documentation of the tools. The line types in ggplot2 are stated to be “based on a set supplied by Richard Pearson, University of Manchester”.

To see what the line styles contribute on their own, we draw the phosphate fractions in black with the line styles of each tool:

[12]:
def compare_tools(case):
    """Draw a case with the line styles of all the tools."""
    fig, axes = plt.subplots(
        constrained_layout=True,
        nrows=5,
        ncols=2,
        figsize=(10, 11),
        sharex=True,
        sharey=True,
    )
    for ax, (tool, (patterns, cap)) in zip(axes.flat, TOOLS.items()):
        xlabel, ylabel = draw_curves(ax, case, patterns, cap)
        ax.set_title(tool, loc="left", fontsize=11)
    for ax in axes[-1]:
        ax.set_xlabel(xlabel)
    for ax in axes[:, 0]:
        ax.set_ylabel(ylabel)
    sns.despine(fig=fig)


compare_tools("Phosphate fractions")
../../../_images/posts_2026_linestyles_linestyles_26_0.png

The curves are easiest to follow for the sets where the three patterns are of different kinds (a dashed, a dotted and a dash-dotted line), as in matplotlib, seaborn, R, Makie and the handplukka set. For ggplot2, plotly and Grace, two or three of the patterns are dashes of different lengths, and these are harder to tell apart on the steep parts of the curves.

The long gaps in gnuplot and plotly break the curves into pieces, and the dotted lines in Grace and gnuplot have so little ink that they almost disappear next to the solid line.

These are my impressions from looking at the figure, and it would be good to have some numbers to go with them.

A distance between dash patterns#

For colours, we could calculate how far apart two colours are, and the colours by Petroff were selected with such a distance. A distance between dash patterns would let us do the same for line styles.

For dash patterns, there are fewer measurements to build on. The most useful I have found is by Sterzik et al., who measured how small a difference in the dashing of two lines people can see. From this, they give 13 levels of dashing that can be told apart, in two series. All the lines were two pixels wide and had round ends:

  • In the first series, the dashes and the gaps grow together. A gap is 4 pixels longer than a dash (lengths are given without the round ends).

  • In the second series, the length of a dash and a gap together is fixed at 40 pixels, and the dashes grow as the gaps shrink.

The levels (the lengths of the dashes in pixels) are:

[13]:
LEVELS_TOGETHER = np.array(
    [0, 1.5, 3.2, 5.2, 7.5, 10.1, 13.1, 16.6, 20.6, 25.2, 30.5, 36.6, 43.6]
)
LEVELS_FIXED = np.array(
    [0, 3.5, 7.1, 10.9, 14.8, 18.9, 23.2, 27.7, 31.9, 34.9, 37.1, 38.7, 39.8]
)

# The difference between the levels in the first series, in line widths:
length = LEVELS_TOGETHER[:-1] / 2.0
step = np.diff(LEVELS_TOGETHER) / 2.0
slope, intercept = np.polyfit(length, step, 1)
fitted = intercept + slope * length

print(f"Step = {intercept:.2f} + {slope:.3f} × length")
print(f"The steps go from {step.min():.2f} to {step.max():.2f} line widths.")
largest = np.abs(step - fitted).max()
print(f"Largest difference from the line: {largest:.3f} line widths.")

# To show the steps together with the fitted line, remove the "# " at the
# start of the lines below:
# fig, ax = plt.subplots(constrained_layout=True, figsize=(5, 3.5))
# ax.plot(length, step, "o", color=COLOURS[0], mfc="none", mew=1.5)
# ax.plot(length, fitted, color=COLOURS[1], lw=LINE_WIDTH)
# ax.set(
#     xlabel="Length of dash (line widths)",
#     ylabel="Step to next level (line widths)",
# )
# sns.despine(fig=fig)
Step = 0.75 + 0.151 × length
The steps go from 0.75 to 3.50 line widths.
Largest difference from the line: 0.014 line widths.

The step to the next level grows linearly with the length of the dash (remove the comments in the code above to see this in a figure). The 12 steps go from 0.75 to 3.5 line widths, and none of them are more than 0.014 line widths from the line. This is less than the rounding of the levels, which are given to a tenth of a pixel. A short dash must change by about 0.75 line widths for the change to be seen, and a long dash by about 15 % in addition to this.

That the smallest change we can notice is a fixed fraction of what is already there is known as Weber’s law, and it holds for many of our senses. It means that what we perceive grows with the logarithm of the strength of the signal. The lightness in CIELAB is made in a similar way, as the cube root of the intensity of the light. For weak signals, the smallest change we can notice stops shrinking, which is the constant part of the step here.

We can use this to make a scale for lengths where one unit is one step. For a mark or a gap of length \(L\) (in line widths), the step is \(a + bL\), with \(a = 0.75\) line widths and \(b = 0.151\) from the fit above. The scale, \(u(L)\), counts the number of steps from zero up to \(L\). A small piece \(\text{d}L^\prime\) at the length \(L^\prime\) is \(\text{d}L^\prime / (a + bL^\prime)\) steps, and adding up the pieces gives

\[u(L) = \int_0^L \frac{\text{d}L^\prime}{a + bL^\prime} = \frac{1}{b} \ln\left(1 + \frac{bL}{a}\right).\]

To get a distance between two patterns, we compare the lengths of their marks on this scale, and the lengths of their gaps, and use the largest of these two differences. A pattern can have marks of different lengths (as in a dash-dotted line). To compare such patterns, we use the Wasserstein distance between the two sets of lengths. A solid line has no gaps, and it can only be told apart from a pattern by the gaps of the pattern.

When a figure is small or out of focus, the gaps are the first to disappear. We include this as a blur that shrinks the gaps (and lets the marks grow). If a gap closes, the marks on each side of it merge:

[14]:
def scale(length):
    """Convert lengths (in line widths) to the scale u(L) in the text.

    On this scale, one step is one unit.
    """
    length = np.asarray(length, dtype=float)
    return np.log1p(slope * length / intercept) / slope


def blurred(pattern, cap, blur=0.0, longest=40.0):
    """Return the marks and gaps of a pattern as seen with a blur.

    Args:
        pattern: The lengths (mark, gap, mark, gap, ...) in line widths.
        cap: The shape of the line ends ("butt" or "round").
        blur: The blur (in line widths). Each gap is made shorter by
            two times the blur.
        longest: The length used for the mark of a solid line.

    Returns:
        The lengths of the marks and the lengths of the gaps. For a
        solid line, the gaps are returned as an empty list.
    """
    marks, gaps = visible(pattern, cap) if pattern else ([longest], [])
    marks = [mark + 2.0 * blur for mark in marks]
    gaps = [max(gap - 2.0 * blur, 0.0) for gap in gaps]
    if not any(gaps):
        return [longest], []
    # Marks on each side of a gap that has closed are merged. We start
    # after an open gap, so that no mark is split in two:
    first = max(i for i, gap in enumerate(gaps) if gap > 0) + 1
    order = [i % len(gaps) for i in range(first, first + len(gaps))]
    merged, open_gaps = [0.0], []
    for i in order:
        merged[-1] += marks[i]
        if gaps[i] > 0:
            open_gaps.append(gaps[i])
            merged.append(0.0)
    return [min(mark, longest) for mark in merged[:-1]], open_gaps


def distance(pattern1, pattern2, cap, blur=0.0):
    """Calculate the distance between two dash patterns, in steps."""
    marks1, gaps1 = blurred(pattern1, cap, blur=blur)
    marks2, gaps2 = blurred(pattern2, cap, blur=blur)
    if not gaps1 and not gaps2:
        return 0.0
    difference = wasserstein_distance(
        scale(gaps1 or [0.0]), scale(gaps2 or [0.0])
    )
    if gaps1 and gaps2:
        marks = wasserstein_distance(scale(marks1), scale(marks2))
        difference = max(difference, marks)
    return difference

The scale was fitted to the first series of levels, so the distance between two neighbouring levels in this series has to be close to one step. The second series was not used for the scale, and we can use it as a test:

[15]:
together = [(level / 2.0, level / 2.0 + 2.0) for level in LEVELS_TOGETHER]
fixed = [(level / 2.0, 20.0 - level / 2.0) for level in LEVELS_FIXED]

for name, series in (("First series ", together), ("Second series", fixed)):
    steps = [
        distance(series[i], series[i + 1], "butt")
        for i in range(len(series) - 1)
    ]
    print(f"{name}: " + " ".join(f"{i:.1f}" for i in steps))
First series : 0.9 0.9 0.9 0.9 0.9 0.9 0.9 0.9 0.9 0.9 0.9 0.9
Second series: 2.0 1.6 1.3 1.1 1.0 1.0 1.2 1.4 1.2 1.0 0.9 0.7

For the second series, the distances between the levels are between 0.7 and 2.0 steps, where they should have been 1. The scale is correct to within a factor of two. This is not very precise, but it is enough to compare the sets of line styles.

For each set, we find the two patterns that are closest to each other. We also find the smallest blur that brings two of the patterns closer than one step, together with the longest gap and the longest period in the set:

[16]:
NAMES = ["1st", "2nd", "3rd", "4th", "5th", "6th"]


def closest_pair(patterns, cap, blur=0.0):
    """Return the smallest distance in a set, and the pair that has it."""
    pairs = itertools.combinations(range(len(patterns)), 2)
    return min(
        (distance(patterns[i], patterns[j], cap, blur=blur), i, j)
        for i, j in pairs
    )


def merging_blur(patterns, cap):
    """Return the smallest blur that brings two patterns within one step."""
    for blur in np.arange(0.0, 4.0, 0.05):
        if closest_pair(patterns, cap, blur=blur)[0] < 1.0:
            return blur
    return np.nan


def summarise(sets):
    """Print the properties of sets of line styles."""
    print(
        f"{'Set':20s} {'Closest pair (steps)':>24s} {'Merging blur':>14s}"
        f"{'Longest gap':>13s} {'Longest period':>16s}"
    )
    for name, (patterns, cap) in sets.items():
        smallest, i, j = closest_pair(patterns, cap)
        gaps = [max(visible(i, cap)[1]) for i in patterns if i]
        period = max(sum(i) for i in patterns)
        print(
            f"{name:20s} {smallest:10.1f} ({NAMES[i]} and {NAMES[j]})"
            f"{merging_blur(patterns, cap):14.2f} {max(gaps):12.1f}"
            f"{period:16.1f}"
        )


summarise(TOOLS)
Set                      Closest pair (steps)   Merging blur  Longest gap   Longest period
matplotlib                  1.9 (1st and 2nd)          0.40          1.6            10.6
seaborn                     1.2 (1st and 3rd)          0.10          1.5             7.0
R                           1.2 (2nd and 4th)          0.60          3.0            11.0
ggplot2                     1.7 (2nd and 3rd)          0.60          4.0             8.0
Grace                       1.2 (3rd and 4th)          1.10          3.0            10.0
gnuplot                     2.4 (2nd and 4th)          1.60          8.0            18.0
plotly                      1.8 (1st and 2nd)          0.35          7.5            15.0
TikZ                        0.3 (3rd and 4th)          0.00          1.5             4.5
Makie                       1.0 (2nd and 4th)          0.00          3.0            10.0
Handplukka                  1.4 (1st and 4th)          0.20          2.0            10.0

In none of the sets are the two closest patterns more than 2.5 steps apart, and for most of the sets it is between one and two steps. In the experiment, one step was what people needed to tell two lines apart when the lines were shown next to each other. Finding the right curve in a figure from its entry in a legend is a harder task.

For several of the sets (matplotlib, seaborn, plotly and the handplukka set), the closest pair is the solid line and a pattern with short gaps. These gaps close with a blur of less than half a line width. The set with the longest gaps (gnuplot) does best in these numbers, but it was one of the sets that broke the curves into pieces in the figure above. The length of the gaps is a compromise, and the tools have made different choices.

There are things this distance can not tell us. It only knows about lengths, so it does not know if a dash-dotted line is easier to recognise than a dashed line of a different length. I have not found any measurements of this.

With a distance, we can search for a set of line styles in the same way as for colours. We generate candidates (dashes, dots, and combinations of two marks) with round ends, and look for the set where the closest pair is as far apart as possible. To avoid the problems seen above, we require that:

  • No pattern has a period longer than 12 line widths, so that the curves are not broken into long pieces.

  • All the patterns are at least one step apart with a blur of one line width.

[17]:
MARKS = [0.01, 1, 2, 3, 4, 5, 6, 7, 8]
GAPS = [3, 3.5, 4, 4.5, 5]
CAP = "round"

candidates = [()]
for gap in GAPS:
    candidates += [(mark, gap) for mark in MARKS]
    candidates += [
        (long, gap, short, gap)
        for short, long in itertools.combinations(MARKS, 2)
    ]
candidates = [pattern for pattern in candidates if sum(pattern) <= 12.0]


def distance_matrix(blur):
    """Calculate the distances between all the candidates."""
    matrix = np.zeros((len(candidates), len(candidates)))
    for i, j in itertools.combinations(range(len(candidates)), 2):
        matrix[i, j] = distance(candidates[i], candidates[j], CAP, blur=blur)
        matrix[j, i] = matrix[i, j]
    return matrix


sharp = distance_matrix(0.0)
with_blur = distance_matrix(1.0)
# The solid line (the first candidate) is always included, so we only
# need the candidates that can be told apart from it with a blur:
usable = [i for i in range(1, len(candidates)) if with_blur[0, i] >= 1.0]
print(f"{len(candidates)} candidates, {len(usable)} can be used.")


def best_set(size):
    """Find the best set with a solid line and size - 1 other patterns."""
    best = (0.0, None)
    for others in itertools.combinations(usable, size - 1):
        members = np.array((0, *others))
        pairs = np.triu_indices(size, k=1)
        if with_blur[np.ix_(members, members)][pairs].min() < 1.0:
            continue
        smallest = sharp[np.ix_(members, members)][pairs].min()
        if smallest > best[0]:
            best = (smallest, [candidates[i] for i in members])
    return best


found = {}
for size in (2, 3, 4, 5):
    smallest, patterns = best_set(size)
    found[size] = patterns
    text = ", ".join(
        "–".join(f"{i:g}" for i in pattern) for pattern in patterns[1:]
    )
    print(f"{size} lines: closest pair {smallest:.1f} steps (solid, {text})")
72 candidates, 34 can be used.
2 lines: closest pair 3.9 steps (solid, 0.01–5)
3 lines: closest pair 3.9 steps (solid, 0.01–5, 5–5)
4 lines: closest pair 2.7 steps (solid, 0.01–4, 3–4, 8–4)
5 lines: closest pair 1.6 steps (solid, 0.01–4, 2–4, 5–4, 8–4)

With two or three lines, the patterns can be about four steps apart. With four lines, the best we can do with these requirements is just below three steps, and with five lines it is less than two steps. Dash patterns on their own thus work well for up to three lines, and four lines is close to the limit.

The best set for four lines is a solid line together with dots, short dashes and long dashes, all with the same gap. We can compare this set with Grace and the handplukka set:

[18]:
SEARCH = (found[4], CAP)
selected = {
    "Grace": TOOLS["Grace"],
    "Handplukka": TOOLS["Handplukka"],
    "Search": SEARCH,
}
summarise(selected)
Set                      Closest pair (steps)   Merging blur  Longest gap   Longest period
Grace                       1.2 (3rd and 4th)          1.10          3.0            10.0
Handplukka                  1.4 (1st and 4th)          0.20          2.0            10.0
Search                      2.7 (2nd and 3rd)          1.10          3.0            12.0
[19]:
def compare_sets(sets, cases, colours=None):
    """Draw cases (rows) with different sets of line styles (columns)."""
    fig, axes = plt.subplots(
        constrained_layout=True,
        nrows=len(cases),
        ncols=len(sets),
        figsize=(3.4 * len(sets), 2.7 * len(cases)),
        sharex="row",
        sharey="row",
        squeeze=False,
    )
    for i, (row, case) in enumerate(zip(axes, cases)):
        for ax, (name, (patterns, cap)) in zip(row, sets.items()):
            xlabel, ylabel = draw_curves(ax, case, patterns, cap, colours)
            ax.set_xlabel(xlabel)
            if i == 0:
                ax.set_title(name, fontsize=11)
        row[0].set_ylabel(ylabel)
    sns.despine(fig=fig)
    return fig, axes


SELECTED_CASES = [
    "Phosphate fractions",
    "Bessel functions",
    "Van der Waals isotherms",
    "Consecutive reactions",
]

The line styles will be used together with colours, so we draw four of the cases with the three sets and the colours from above:

[20]:
compare_sets(selected, SELECTED_CASES, COLOURS);
../../../_images/posts_2026_linestyles_linestyles_43_0.png

The set from the search keeps the curves apart for the fractions, the isotherms and the reactions. But there is a lot of white space in its dotted line, where the dots are four line widths apart, and the line looks weaker than the others. The dots in the handplukka set are closer together. The distance only knows about lengths, and not about how heavy a line looks, so the numbers favour the set from the search. I prefer the handplukka set, and will use it in the following. For the Bessel functions, none of the three sets make it easy to follow a curve through the crossings.

Some figures have more than four curves, and for six curves we first need two more colours. We find them with a search like the one for the four colours. We try all pairs of colours on the grid, and keep the pair where the closest colours are furthest apart. Six colours can not be as far apart in lightness as four, so in this search the distances in grey scale are multiplied by five, which makes them count less. For more than six curves, petroff10 is a better choice, and Wilke recommends labels on the curves in place of colours when there are more than about eight.

[21]:
def add_two_colours(colours, grey_weight=5.0):
    """Find two colours that are far from a set of colours and each other.

    Args:
        colours: The colours to keep.
        grey_weight: The factor for the distances in grey scale.
    """
    # Colours that are very light, very dark or close to grey are left out:
    keep = (grid_lab[:, 0] > 15) & (grid_lab[:, 0] < 70) & (grid_chroma > 35)
    allowed = grid[keep]
    to_set = distances_in_all_views(allowed, np.array(colours), grey_weight)
    to_set = to_set.min(axis=1)
    score = np.minimum(
        distances_in_all_views(allowed, allowed, grey_weight),
        np.minimum(to_set[:, np.newaxis], to_set[np.newaxis, :]),
    )
    i, j = np.unravel_index(score.argmax(), score.shape)
    return [tuple(allowed[i]), tuple(allowed[j])]


SIX_COLOURS = COLOURS + add_two_colours(COLOURS)

new_colours = ", ".join(to_hex(colour) for colour in SIX_COLOURS[4:])
print(f"The two new colours: {new_colours}")
The two new colours: #0096e1, #783c69

The two new colours are a light blue and a plum. The six colours need six line styles. We run the search for six lines, and compare the result with a set made by hand, where a long dash and a short dash are added to the handplukka set. The figure shows the patterns, together with six Bessel functions and six peaks next to each other:

[22]:
smallest, patterns = best_set(6)
SIX_PATTERNS = [*TOOLS["Handplukka"][0], (9, 3), (2, 2.5)]
six = {"Handplukka + two": (SIX_PATTERNS, CAP), "Search": (patterns, CAP)}
summarise(six)

fig, axes = plt.subplots(
    constrained_layout=True,
    nrows=2,
    ncols=3,
    figsize=(12, 5.5),
    sharex="col",
    gridspec_kw={"width_ratios": [1, 1.5, 1.5]},
)
x = np.linspace(0, 16, 500)
peaks = np.linspace(0, 10, 400)
for row, (name, (patterns, cap)) in zip(axes, six.items()):
    for i, (pattern, colour) in enumerate(zip(patterns, SIX_COLOURS)):
        settings = {
            "color": colour,
            "lw": LINE_WIDTH,
            "dashes": pattern,
            "dash_capstyle": cap,
        }
        row[0].plot([0, 1], [-i, -i], **settings)
        row[1].plot(x, jv(i, x), **settings)
        row[2].plot(
            peaks, np.exp(-((peaks - 1.5 - 1.4 * i) ** 2) / 1.5), **settings
        )
    row[0].set_title(name, loc="left", fontsize=11)
    row[0].set_axis_off()
sns.despine(fig=fig)
Set                      Closest pair (steps)   Merging blur  Longest gap   Longest period
Handplukka + two            1.4 (1st and 4th)          0.20          2.0            12.0
Search                      1.3 (2nd and 6th)          1.10          3.0            11.0
../../../_images/posts_2026_linestyles_linestyles_48_1.png

With six lines, the closest patterns from the search are 1.3 steps apart, down from just below three steps with four lines. Six line styles are close to what can be told apart at all, and they need the colours. The set made by hand has about the same distance between its closest patterns (1.4 steps, between the solid and the dotted line, as in the handplukka set), but its patterns come within one step of each other with a smaller blur. As for four lines, the lines in the set made by hand are more equal in weight. I will use this set together with the six colours.

Figures in black and white#

In a figure in black and white, the lines do not have to be black. The lightness was what kept the colours apart in grey scale, and we can use it directly by drawing the lines in different shades of grey. Lines that are too light are hard to see on a white background, so there is room for about four shades between black and a light grey. The shades can also be combined with the dash patterns. A dotted line has less ink than a solid line and looks lighter, so we give the darkest shade to the pattern with the least ink, and the lightest shade to the solid line:

[23]:
GREYS = [(shade, shade, shade) for shade in (0.0, 0.33, 0.52, 0.68)]

patterns, cap = TOOLS["Handplukka"]
order = np.argsort([ink_fraction(pattern, cap) for pattern in patterns])
paired = [None] * len(patterns)
for shade, i in zip(GREYS, order):
    paired[i] = shade

fig, axes = plt.subplots(
    constrained_layout=True,
    nrows=2,
    ncols=2,
    figsize=(7.0, 5.4),
    sharex="row",
    sharey="row",
)
titles = ["Shades of grey", "Shades of grey with dashes"]
for ax, title in zip(axes[0], titles):
    ax.set_title(title, fontsize=11)
for row, case in zip(axes, ["Phosphate fractions", "Bessel functions"]):
    draw_curves(row[0], case, [()] * 4, "butt", GREYS)
    xlabel, ylabel = draw_curves(row[1], case, patterns, cap, paired)
    for ax in row:
        ax.set_xlabel(xlabel)
    row[0].set_ylabel(ylabel)
sns.despine(fig=fig)
../../../_images/posts_2026_linestyles_linestyles_51_0.png

With the shades alone, the curves can be told apart for the fractions. For the Bessel functions, the two shades in the middle are hard to keep apart after a few crossings. With both shades and dashes, there are two things that separate each pair of curves.

Using the colours and the line styles#

The six colours and the six dash patterns I ended up with can be used in other figures by storing them in a style file for matplotlib. The file sets the colours and the line styles that matplotlib cycles through when lines are added to a figure, and it makes the ends of the dashes round. The first four are the dark blue, red, yellow and black, with the handplukka line styles:

[24]:
patterns, cap = SIX_PATTERNS, CAP
colours = ", ".join(f"'{to_hex(colour)[1:]}'" for colour in SIX_COLOURS)
linestyles = ", ".join(
    f"(0, {pattern})" if pattern else "'-'" for pattern in patterns
)
lines = [
    "# Colours and line styles from the post on line styles at andersle.no.",
    f"axes.prop_cycle: cycler('color', [{colours}])"
    f" + cycler('linestyle', [{linestyles}])",
    f"lines.dash_capstyle: {cap}",
    f"lines.linewidth: {LINE_WIDTH}",
    "legend.handlelength: 3.2",
]
with open("linestyles.mplstyle", "w", encoding="utf8") as output:
    output.write("\n".join(lines) + "\n")
print("\n".join(lines))
# Colours and line styles from the post on line styles at andersle.no.
axes.prop_cycle: cycler('color', ['002da5', 'd22d3c', 'dc9a1e', '000000', '0096e1', '783c69']) + cycler('linestyle', ['-', (0, (5, 3)), (0, (5, 2.5, 0.01, 2.5)), (0, (0.01, 2.2)), (0, (9, 3)), (0, (2, 2.5))])
lines.dash_capstyle: round
lines.linewidth: 2.0
legend.handlelength: 3.2

With the style, the colours and the dashes are applied without any settings for the individual lines:

[25]:
with plt.style.context("linestyles.mplstyle"):
    fig, ax = plt.subplots(constrained_layout=True, figsize=(6, 3.5))
    x, curves, xlabel, ylabel = CASES["Phosphate fractions"]()
    for label, y in curves.items():
        ax.plot(x, y, label=label)
    ax.set(xlabel=xlabel, ylabel=ylabel)
    ax.legend(
        frameon=False,
        ncols=4,
        loc="lower center",
        bbox_to_anchor=(0.5, 1.0),
        columnspacing=1.0,
    )
    sns.despine(fig=fig)
../../../_images/posts_2026_linestyles_linestyles_56_0.png

The style file is stored together with this notebook, and matplotlib can read it directly from there:

from matplotlib import pyplot as plt

plt.style.use(
    "https://raw.githubusercontent.com/andersle/andersleno/main/"
    "2026/linestyles/linestyles.mplstyle"
)

With seaborn, the style has to be loaded after the call to sns.set_theme, since the theme sets its own colours. The settings in the file can also be copied into a style file of your own, and the colours and the dash patterns changed there.

Summary#

The plotting tools I looked at come with dash patterns that are quite different from each other, and I did not find reasons given for the choices. This is what I will do in my own figures:

  • Select colours that differ in lightness, and not only in hue. Then the curves can also be told apart in grey scale.

  • Use dashes together with the colours. This works best for up to four curves, and six is about the limit. The patterns should be of different kinds (dashes, dots, and dashes with dots). The gaps should not be so short that they disappear in a small figure, and not so long that the curve is broken into pieces.

  • Use shades of grey together with the dashes for figures in black and white.

The colours and the line styles are available as a style file for matplotlib, as described in the last section.

References#