Making a discrete colormap/colorbar in Python with matplotlib

Every so often I want to make a plot with a discrete colormap and colorbar instead of the default continuous map. Searches usually bring me to a post suggesting matplotlib.colors.LinearSegmentedColormap or some complicated thing. For my purposes, it’s as simple as:

cmap = plt.get_cmap('viridis', 11)

where 'viridis' can be replaced with any colormap name, and 11 is replaced with the number of levels desired. Then cmap can be passed to your plot function (e.g., plt.pcolormesh(A, cmap=cmap)). Here’s the documentation for plt.get_cmap()