diff --git a/CHANGELOG.md b/CHANGELOG.md index db4e007..bfea00e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -40,6 +40,11 @@ - Ensure the current axes (`plt.gca()`) is not changed by calling `mpu.colorbar(...)` ([#136](https://github.com/mathause/mplotutils/pull/136)). +### Internal changes + +- Align internal usage of `ListedColormaps` with changes in [matplotlib/matplotlib#29135](https://github.com/matplotlib/matplotlib/pull/29135) + ([#145](https://github.com/mathause/mplotutils/pull/145), and [#147](https://github.com/mathause/mplotutils/pull/147)). + ## v0.5.0 (27.03.2024) Version v0.5.0 aligns passing multiple axes to `colorbar` with matplotlib. diff --git a/mplotutils/_colormaps.py b/mplotutils/_colormaps.py index d29fb64..b87e673 100644 --- a/mplotutils/_colormaps.py +++ b/mplotutils/_colormaps.py @@ -1,3 +1,5 @@ +import itertools + import matplotlib as mpl import numpy as np from matplotlib.colors import from_levels_and_colors @@ -54,7 +56,8 @@ def _color_palette(cmap, n_colors): colors_i = np.linspace(0, 1.0, n_colors) if isinstance(cmap, (list, tuple)): - # we have a list of colors + # expand or truncate the list of colors to n_colors + cmap = list(itertools.islice(itertools.cycle(cmap), n_colors)) cmap = ListedColormap(cmap) pal = cmap(colors_i) elif isinstance(cmap, str): diff --git a/mplotutils/tests/test_colormap.py b/mplotutils/tests/test_colormap.py index c8f0311..fcafaa4 100644 --- a/mplotutils/tests/test_colormap.py +++ b/mplotutils/tests/test_colormap.py @@ -77,8 +77,25 @@ def test_from_levels_and_cmap_seaborn_cmap(): def test_from_levels_and_cmap_colorstring(): - pytest.importorskip("seaborn") levels = [1, 2, 3] cmap, norm = mpu.from_levels_and_cmap(levels, "0.1") assert_cmap_norm(cmap, norm, levels, extend="neither") + + np.testing.assert_equal(cmap.colors[0], np.array([0.1, 0.1, 0.1, 1.0])) + np.testing.assert_equal(cmap.colors[1], np.array([0.1, 0.1, 0.1, 1.0])) + + +def test_from_levels_and_cmap_color_list_explicit(): + + levels = [1, 2, 3, 4, 5] + + # ensure colors are repeated (although that can also be unexpected) + cmap, norm = mpu.from_levels_and_cmap(levels, ["b", "k"]) + + assert_cmap_norm(cmap, norm, levels, extend="neither") + + np.testing.assert_equal(cmap.colors[0], np.array([0.0, 0.0, 1.0, 1.0])) # blue + np.testing.assert_equal(cmap.colors[1], np.array([0.0, 0.0, 0.0, 1.0])) # black + np.testing.assert_equal(cmap.colors[2], np.array([0.0, 0.0, 1.0, 1.0])) # blue + np.testing.assert_equal(cmap.colors[3], np.array([0.0, 0.0, 0.0, 1.0])) # black