I have been investigating these ideas and here is my five cents worth. It avoids calling BoundaryNorm
as well as specifying norm
as an argument to scatter
and colorbar
. However I have found no way of eliminating the rather long-winded call to matplotlib.colors.LinearSegmentedColormap.from_list
.
Some background is that matplotlib provides so-called qualitative colormaps, intended to use with discrete data. Set1
, e.g., has 9 easily distinguishable colors, and tab20
could be used for 20 colors. With these maps it could be natural to use their first n colors to color scatter plots with n categories, as the following example does. The example also produces a colorbar with n discrete colors approprately labelled.
import matplotlib, numpy as np, matplotlib.pyplot as plt
n = 5
from_list = matplotlib.colors.LinearSegmentedColormap.from_list
cm = from_list(None, plt.cm.Set1(range(0,n)), n)
x = np.arange(99)
y = x % 11
z = x % n
plt.scatter(x, y, c=z, cmap=cm)
plt.clim(-0.5, n-0.5)
cb = plt.colorbar(ticks=range(0,n), label='Group')
cb.ax.tick_params(length=0)
which produces the image below. The n
in the call to Set1
specifies
the first n
colors of that colormap, and the last n
in the call to from_list
specifies to construct a map with n
colors (the default being 256). In order to set cm
as the default colormap with plt.set_cmap
, I found it to be necessary to give it a name and register it, viz:
cm = from_list('Set15', plt.cm.Set1(range(0,n)), n)
plt.cm.register_cmap(None, cm)
plt.set_cmap(cm)
...
plt.scatter(x, y, c=z)