Styles, Palettes and Colormaps#
braintools.visualize provides Matplotlib styles, color palettes and colormaps for neuroscience figures:
Function |
Does |
|---|---|
|
set Matplotlib |
|
applies a style by name; usable as a context manager |
|
returns a list of colors |
|
build and register colormaps |
|
changes the colors of the |
This notebook shows how to apply styles without side effects, how to check that a palette works for color-blind readers, and how to choose a colormap.
1. Setup#
import matplotlib.pyplot as plt
import numpy as np
import braintools
plt.rcParams["figure.dpi"] = 80
rng = np.random.default_rng(6)
t = np.linspace(0, 1, 300)
traces = [np.sin(2 * np.pi * (3 + k) * t) * np.exp(-2 * t) + 0.4 * k for k in range(4)]
counts = rng.gamma(2, 2, 400)
def demo_figure(title):
fig, ax = plt.subplots(1, 2, figsize=(8, 2.8))
for k, tr in enumerate(traces):
ax[0].plot(t, tr, label=f"neuron {k}")
ax[0].set_xlabel("Time (s)"); ax[0].set_ylabel("v"); ax[0].legend(fontsize=7)
ax[1].hist(counts, bins=25); ax[1].set_xlabel("Rate (Hz)"); ax[1].set_ylabel("Neurons")
fig.suptitle(title)
fig.tight_layout()
return fig
2. Applying Styles#
The style functions modify the global rcParams: every figure created afterwards, in the whole session, uses them. apply_style(name, **kwargs) applies the same styles, and when used as a context manager it restores the previous settings on exit:
for name in ["neural", "publication", "dark", "colorblind"]:
kwargs = {"dpi": 80} if name == "publication" else {}
with braintools.visualize.apply_style(name, **kwargs):
demo_figure(f"apply_style('{name}')")
plt.show()
print("restored after the with-blocks:", plt.rcParams["axes.facecolor"], plt.rcParams["figure.dpi"])
restored after the with-blocks: white 80.0
Styles take effect when figures and artists are created, so create the figure inside the block. What each style changes:
neural_style: light gray background, grid, larger fonts, and a color cycle ofspike_color,membrane_colorand three palette colors;membrane_coloris also the default fill of bars and patches.publication_style: serif fonts, no top/right spines, thin lines, PDF as the defaultsavefigformat, andfigsize/dpifor both the screen and saved files. The defaultdpi=300makes every inline figure in a notebook enormous; pass a screen DPI here anddpi=...tosavefiginstead.dark_style: dark background and light text;accent_coloris the first line color.colorblind_friendly_style: only replaces the color cycle (see below).
3. Palettes and Color Blindness#
get_color_palette(name, n_colors) returns the 'neural', 'colorblind' or 'dark' palette as hex strings, repeating colors when more are requested than the palette has. The 'colorblind' palette (also used by colorblind_friendly_style) is the Okabe–Ito palette, designed to stay distinguishable for the common forms of color-vision deficiency.
We can check that claim by simulating deuteranopia (the most common deficiency, missing green-sensitive cones) with the transformation of Machado et al. (2009), and measuring how close the closest pair of colors becomes. For comparison, Matplotlib’s default cycle tab10:
from matplotlib.colors import to_rgb
def srgb_to_linear(c):
c = np.asarray(c)
return np.where(c <= 0.04045, c / 12.92, ((c + 0.055) / 1.055) ** 2.4)
def linear_to_srgb(c):
c = np.clip(c, 0, 1)
return np.where(c <= 0.0031308, 12.92 * c, 1.055 * c ** (1 / 2.4) - 0.055)
DEUTERANOPIA = np.array([[0.367322, 0.860646, -0.227968], # Machado et al. 2009, severity 1
[0.280085, 0.672501, 0.047413],
[-0.011820, 0.042940, 0.968881]])
def simulate(colors):
rgb = srgb_to_linear([to_rgb(c) for c in colors])
return linear_to_srgb(rgb @ DEUTERANOPIA.T)
def min_distance(rgb):
d = np.linalg.norm(rgb[:, None] - rgb[None], axis=-1)
return d[np.triu_indices(len(rgb), 1)].min()
palettes = {"tab10 (Matplotlib default)": plt.cm.tab10.colors[:8],
"colorblind (Okabe-Ito)": braintools.visualize.get_color_palette("colorblind"),
"neural": braintools.visualize.get_color_palette("neural")}
fig, axes = plt.subplots(len(palettes), 2, figsize=(9, 3.2))
for row, (name, colors) in zip(axes, palettes.items()):
normal = np.array([to_rgb(c) for c in colors])
deut = simulate(colors)
for a, rgb, label in [(row[0], normal, name), (row[1], deut, "simulated deuteranopia")]:
a.imshow(rgb[None], aspect="auto"); a.set_xticks([]); a.set_yticks([]); a.set_title(label, fontsize=9)
print(f"{name:28s} closest pair: normal vision {min_distance(normal):.3f}, deuteranopia {min_distance(deut):.3f}")
plt.tight_layout(); plt.show()
tab10 (Matplotlib default) closest pair: normal vision 0.265, deuteranopia 0.115
colorblind (Okabe-Ito) closest pair: normal vision 0.263, deuteranopia 0.202
neural closest pair: normal vision 0.088, deuteranopia 0.087
Under simulated deuteranopia two pairs of tab10 colors (green and red, blue and purple) move close together, the minimum distance dropping to less than half, while the Okabe–Ito colors keep a clear minimum distance. The 'neural' palette is decorative rather than accessible: some of its pastel colors are hard to tell apart even with normal vision. When colors must carry information, use the colorblind palette, and add a second cue (line style, marker, direct labels) where possible.
set_default_colors({...}) updates the colors of the 'neural' palette; the color cycle of neural_style uses three of them (excitatory, inhibitory, synapse), its first two colors come from its spike_color and membrane_color arguments.
4. Colormaps#
brain_colormaps() registers four colormaps with Matplotlib, after which they can be used by name: 'membrane', 'spikes', 'connectivity' and 'brain_activation'. create_neural_colormap(name, colors) builds and registers a colormap from any list of colors.
A colormap for continuous data should change perceived lightness monotonically; otherwise the eye sees boundaries that are not in the data. We compute the CIE lightness \(L^*\) along each colormap:
braintools.visualize.brain_colormaps()
braintools.visualize.create_neural_colormap("my_rate", ["#000004", "#3B0F70", "#8C2981", "#DE4968", "#FE9F6D", "#FCFDBF"])
def lightness(cmap_name, n=256):
rgb = plt.get_cmap(cmap_name)(np.linspace(0, 1, n))[:, :3]
Y = srgb_to_linear(rgb) @ np.array([0.2126, 0.7152, 0.0722])
f = np.where(Y > (6 / 29) ** 3, np.cbrt(Y), Y / (3 * (6 / 29) ** 2) + 4 / 29)
return 116 * f - 16
names = ["viridis", "membrane", "spikes", "connectivity", "brain_activation", "my_rate"]
gradient = np.linspace(0, 1, 256)[None]
fig, ax = plt.subplots(1, 2, figsize=(12, 3.8), gridspec_kw={"width_ratios": [1, 1.2]})
for k, name in enumerate(names):
ax[0].imshow(gradient, aspect="auto", cmap=name, extent=[0, 1, k, k + 0.8])
L = lightness(name)
ax[1].plot(np.linspace(0, 1, 256), L, label=name)
print(f"{name:17s} L* from {L[0]:5.1f} to {L[-1]:5.1f}, monotonic: {bool(np.all(np.diff(L) > -1e-3) or np.all(np.diff(L) < 1e-3))}")
ax[0].set_yticks(np.arange(len(names)) + 0.4); ax[0].set_yticklabels(names); ax[0].set_xticks([])
ax[1].set_xlabel("position in colormap"); ax[1].set_ylabel("lightness L*"); ax[1].legend(fontsize=8)
plt.tight_layout(); plt.show()
viridis L* from 14.9 to 90.9, monotonic: True
membrane L* from 52.5 to 46.5, monotonic: False
spikes L* from 5.1 to 100.0, monotonic: True
connectivity L* from 14.9 to 90.9, monotonic: True
brain_activation L* from 13.0 to 53.2, monotonic: False
my_rate L* from 0.1 to 97.9, monotonic: True
viridis, 'spikes', 'connectivity' and the custom 'my_rate' (built from magma-like colors) increase in lightness monotonically and are suitable for sequential data such as rates or weights. 'membrane' and 'brain_activation' do not: 'brain_activation' is a rainbow-like map whose lightness rises and falls, so equal steps in the data look unequal and its bright cyan and yellow bands draw the eye to arbitrary values. Use such maps only for categorical-like displays, not for quantities.
The same rate map in a rainbow-like map and a monotonic one:
gx, gy = np.meshgrid(np.linspace(-1, 1, 120), np.linspace(-1, 1, 120))
smooth = np.exp(-(gx ** 2 + gy ** 2) / 0.5) # a single smooth bump, no edges
fig, ax = plt.subplots(1, 2, figsize=(9, 4))
for a, cmap in zip(ax, ["brain_activation", "my_rate"]):
braintools.visualize.firing_rate_map(smooth, cmap=cmap, ax=a, title=cmap, show_colorbar=False)
plt.tight_layout(); plt.show()
The data is one smooth bump; in the rainbow-like map it appears as a sequence of rings with sharp borders.
Summary#
Style functions change global
rcParams; wrap figures inwith apply_style(name, ...):to keep the change local, and create the figure inside the block.publication_stylesetsfigure.dpitoo; pass a screen DPI in notebooks and choose the file DPI insavefig.The
'colorblind'palette (Okabe–Ito) stays distinguishable under simulated deuteranopia, unlike Matplotlib’s default cycle.brain_colormaps()registers four colormaps; prefer the monotonic ones ('spikes','connectivity', orviridis) for continuous data, and build your own withcreate_neural_colormap.