mszep
mszep

Reputation: 420

How to display a given number of colors in a matplotlib contourf and colorbar

I have a 2D surface with several regions, that I would like to plot as different colors, each color standing for a given region.

The issue I'm having is that my colorbar is not spacing the different colors uniformly (when using 5 regions), or displaying the right number of regions (when using 9 regions).

My code based on this example:

import matplotlib as mpl
import matplotlib.pyplot as plt

cmap = ListedColormap([str(x) for x in np.linspace(0.0, 1.0, 5)])

# If a ListedColormap is used, the length of the bounds array must be
# one greater than the length of the color list.  The bounds must be
# monotonically increasing.
bounds = np.linspace(0.0, 1.0, 6)
norm = mpl.colors.BoundaryNorm(bounds, cmap.N)
plt.contourf(np.array([[1.0, 1.5, 2.0, 2.5, 3.0], [3.5, 4.0, 4.5, 5.0, 5.0]]), cmap=cmap)
cb2 = plt.colorbar(cmap=cmap, norm=norm)

and the results:

five levels, note the uneven spacing in the colorbar

nine levels, note that there are eight levels in the colorbar (the lowest two are very slightly different

I don't know what's causing this, or how to fix it.

Upvotes: 2

Views: 1757

Answers (1)

Amy Teegarden
Amy Teegarden

Reputation: 3972

If you don't specify the levels, matplotlib chooses them automatically. You can specify using the keyword levels. So, for example, if you wanted 5 regions spaced evenly from 1 to 5, you could use plt.contourf(np.array([[1.0, 1.5, 2.0, 2.5, 3.0], [3.5, 4.0, 4.5, 5.0, 5.0]]), cmap=cmap, levels = np.linspace(1.0, 5.0, 6))

Upvotes: 6

Related Questions