|
| 1 | +New "extend" keyword to colors.BoundaryNorm |
| 2 | +------------------------------------------- |
| 3 | + |
| 4 | +`~.colors.BoundaryNorm` now has an ``extend`` kwarg, |
| 5 | +analogous to ``extend`` in ~.axes._axes.Axes.contourf`. When set to |
| 6 | +'both', 'min', or 'max', it interpolates such that the corresponding |
| 7 | +out-of-range values are mapped to colors distinct from their in-range |
| 8 | +neighbors. The colorbar inherits the ``extend`` argument from the |
| 9 | +norm, so with ``extend='both'``, for example, the colorbar will have |
| 10 | +triangular extensions for out-of-range values with colors that differ |
| 11 | +from adjacent colors. |
| 12 | + |
| 13 | + .. plot:: |
| 14 | + |
| 15 | + import matplotlib.pyplot as plt |
| 16 | + from matplotlib.colors import BoundaryNorm |
| 17 | + import numpy as np |
| 18 | + |
| 19 | + # Make the data |
| 20 | + dx, dy = 0.05, 0.05 |
| 21 | + y, x = np.mgrid[slice(1, 5 + dy, dy), |
| 22 | + slice(1, 5 + dx, dx)] |
| 23 | + z = np.sin(x) ** 10 + np.cos(10 + y * x) * np.cos(x) |
| 24 | + z = z[:-1, :-1] |
| 25 | + |
| 26 | + # Z roughly varies between -1 and +1. |
| 27 | + # Color boundary levels range from -0.8 to 0.8, so there are out-of-bounds |
| 28 | + # areas. |
| 29 | + levels = [-0.8, -0.5, -0.2, 0.2, 0.5, 0.8] |
| 30 | + cmap = plt.get_cmap('PiYG') |
| 31 | + |
| 32 | + fig, axs = plt.subplots(nrows=2, constrained_layout=True, sharex=True) |
| 33 | + |
| 34 | + # Before this change: |
| 35 | + norm = BoundaryNorm(levels, ncolors=cmap.N) |
| 36 | + im = axs[0].pcolormesh(x, y, z, cmap=cmap, norm=norm) |
| 37 | + fig.colorbar(im, ax=axs[0], extend='both') |
| 38 | + axs[0].axis([x.min(), x.max(), y.min(), y.max()]) |
| 39 | + axs[0].set_title("Colorbar with extend='both'") |
| 40 | + |
| 41 | + # With the new keyword: |
| 42 | + norm = BoundaryNorm(levels, ncolors=cmap.N, extend='both') |
| 43 | + im = axs[1].pcolormesh(x, y, z, cmap=cmap, norm=norm) |
| 44 | + fig.colorbar(im, ax=axs[1]) # note that the colorbar is updated accordingly |
| 45 | + axs[1].axis([x.min(), x.max(), y.min(), y.max()]) |
| 46 | + axs[1].set_title("BoundaryNorm with extend='both'") |
| 47 | + |
| 48 | + plt.show() |
0 commit comments