Cyclic colormap without visual distortions for use in phase angle plots?

As of matplotlib version 3.0 there are built-in cyclic perceptually uniform colormaps. OK, just the one colormap for the time being, but with two choices of start and end along the cycle, namely twilight and twilight_shifted.

A short example to demonstrate how they look:

import matplotlib.pyplot as plt
import numpy as np

# example data: argument of complex numbers around 0
N = 100
re, im = np.mgrid[-1:1:100j, -1:1:100j]
angle = np.angle(re + 1j*im)

cmaps = 'twilight', 'twilight_shifted'
fig, axs = plt.subplots(ncols=len(cmaps), figsize=(9.5, 5.5))
for cmap, ax in zip(cmaps, axs):
    cf = ax.pcolormesh(re, im, angle, shading='gouraud', cmap=cmap)
    ax.set_title(cmap)
    ax.set_xlabel(r'$\operatorname{Re} z$')
    ax.set_ylabel(r'$\operatorname{Im} z$')
    ax.axis('scaled')

    cb = plt.colorbar(cf, ax=ax, orientation='horizontal')
    cb.set_label(r'$\operatorname{Arg} z$')
fig.tight_layout()

The above produces the following figure:

twilight and twilight_shifted colormaps in action

These brand new colormaps are an amazing addition to the existing collection of perceptually uniform (sequential) colormaps, namely viridis, plasma, inferno, magma and cividis (the last one was a new addition in 2.2 which is not only perceptually uniform and thus colorblind-friendly, but it should look as close as possible to colorblind and non-colorblind people).


EDIT: Matplotlib has now nice cyclic color maps, see the answer of @andras-deak below. They use a similar approach to the color maps as in this answer, but smooth the edges in luminosity.

The issue with the hue-HUSL colormap is that it's not intuitive to read an angle from it. Therefore, I suggest to make your own colormap. Here's a few possibilities:

  • For the linear segmented colormap, we definine a few colors. The colormap is then a linear interpolation between the colors. This has visual distortions.
  • For the luminosity-HSLUV map, we use the HUSL ("HSLUV") space, however instead of just hue channel, we use two colors and the luminosity channel. This has distortions in the chroma, but has bright colors.
  • The luminosity-HPLUV map, we use the HPLUV color space (following @mwaskom's comment). This is the only way to really have no visual distortions, but the colors are not saturated This is what they look like:

colormap with simple function

We see that in our custom colormaps, white stands for 0, blue stands for 1i, etc. On the upper right, we see the hue-HUSL map for comparison. There, the color-angle assignments are random.

enter image description here

Also when plotting a more complex function, it's straightforward to read out the phase of the result when using one of our colormaps.

And here's the code for the plots:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as col
import seaborn as sns
import hsluv # install via pip
import scipy.special # just for the example function

##### generate custom colormaps
def make_segmented_cmap(): 
    white = '#ffffff'
    black = '#000000'
    red = '#ff0000'
    blue = '#0000ff'
    anglemap = col.LinearSegmentedColormap.from_list(
        'anglemap', [black, red, white, blue, black], N=256, gamma=1)
    return anglemap

def make_anglemap( N = 256, use_hpl = True ):
    h = np.ones(N) # hue
    h[:N//2] = 11.6 # red 
    h[N//2:] = 258.6 # blue
    s = 100 # saturation
    l = np.linspace(0, 100, N//2) # luminosity
    l = np.hstack( (l,l[::-1] ) )

    colorlist = np.zeros((N,3))
    for ii in range(N):
        if use_hpl:
            colorlist[ii,:] = hsluv.hpluv_to_rgb( (h[ii], s, l[ii]) )
        else:
            colorlist[ii,:] = hsluv.hsluv_to_rgb( (h[ii], s, l[ii]) )
    colorlist[colorlist > 1] = 1 # correct numeric errors
    colorlist[colorlist < 0] = 0 
    return col.ListedColormap( colorlist )

N = 256
segmented_cmap = make_segmented_cmap()
flat_huslmap = col.ListedColormap(sns.color_palette('husl',N))
hsluv_anglemap = make_anglemap( use_hpl = False )
hpluv_anglemap = make_anglemap( use_hpl = True )

##### generate data grid
x = np.linspace(-2,2,N)
y = np.linspace(-2,2,N)
z = np.zeros((len(y),len(x))) # make cartesian grid
for ii in range(len(y)): 
    z[ii] = np.arctan2(y[ii],x) # simple angular function
    z[ii] = np.angle(scipy.special.gamma(x+1j*y[ii])) # some complex function

##### plot with different colormaps
fig = plt.figure(1)
fig.clf()
colormapnames = ['segmented map', 'hue-HUSL', 'lum-HSLUV', 'lum-HPLUV']
colormaps = [segmented_cmap, flat_huslmap, hsluv_anglemap, hpluv_anglemap]
for ii, cm in enumerate(colormaps):
    ax = fig.add_subplot(2, 2, ii+1)
    pmesh = ax.pcolormesh(x, y, z/np.pi, 
        cmap = cm, vmin=-1, vmax=1)
    plt.axis([x.min(), x.max(), y.min(), y.max()])
    cbar = fig.colorbar(pmesh)
    cbar.ax.set_ylabel('Phase [pi]')
    ax.set_title( colormapnames[ii] )
plt.show()

You could try the "husl" system, which is similar to hls/hsv but with better visual properties. It is available in seaborn and as a standalone package.

Here's a simple example:

import numpy as np
from numpy import sin, cos, pi
import matplotlib.pyplot as plt
import seaborn as sns

n = 314
theta = np.linspace(0, 2 * pi, n)

x = cos(theta)
y = sin(theta)

f = plt.figure(figsize=(10, 5))
with sns.color_palette("husl", n):
    ax = f.add_subplot(121)
    ax.plot([np.zeros_like(x), x], [np.zeros_like(y), y], lw=3)
    ax.set_axis_off()
    ax.set_title("HUSL space")

with sns.color_palette("hls", n):
    ax = f.add_subplot(122)
    ax.plot([np.zeros_like(x), x], [np.zeros_like(y), y], lw=3)
    ax.set_axis_off()
    ax.set_title("HLS space")

f.tight_layout()

enter image description here