Skip to content

Commit 53d1d1b

Browse files
authored
ListedColormap: repeat colors if necessary (#147)
* ListedColormap: repeat colors if necessary * changelog
1 parent cff3381 commit 53d1d1b

File tree

3 files changed

+27
-2
lines changed

3 files changed

+27
-2
lines changed

CHANGELOG.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,11 @@
4040

4141
- Ensure the current axes (`plt.gca()`) is not changed by calling `mpu.colorbar(...)` ([#136](https://github.com/mathause/mplotutils/pull/136)).
4242

43+
### Internal changes
44+
45+
- Align internal usage of `ListedColormaps` with changes in [matplotlib/matplotlib#29135](https://github.com/matplotlib/matplotlib/pull/29135)
46+
([#145](https://github.com/mathause/mplotutils/pull/145), and [#147](https://github.com/mathause/mplotutils/pull/147)).
47+
4348
## v0.5.0 (27.03.2024)
4449

4550
Version v0.5.0 aligns passing multiple axes to `colorbar` with matplotlib.

mplotutils/_colormaps.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import itertools
2+
13
import matplotlib as mpl
24
import numpy as np
35
from matplotlib.colors import from_levels_and_colors
@@ -54,7 +56,8 @@ def _color_palette(cmap, n_colors):
5456

5557
colors_i = np.linspace(0, 1.0, n_colors)
5658
if isinstance(cmap, (list, tuple)):
57-
# we have a list of colors
59+
# expand or truncate the list of colors to n_colors
60+
cmap = list(itertools.islice(itertools.cycle(cmap), n_colors))
5861
cmap = ListedColormap(cmap)
5962
pal = cmap(colors_i)
6063
elif isinstance(cmap, str):

mplotutils/tests/test_colormap.py

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -77,8 +77,25 @@ def test_from_levels_and_cmap_seaborn_cmap():
7777

7878

7979
def test_from_levels_and_cmap_colorstring():
80-
pytest.importorskip("seaborn")
8180

8281
levels = [1, 2, 3]
8382
cmap, norm = mpu.from_levels_and_cmap(levels, "0.1")
8483
assert_cmap_norm(cmap, norm, levels, extend="neither")
84+
85+
np.testing.assert_equal(cmap.colors[0], np.array([0.1, 0.1, 0.1, 1.0]))
86+
np.testing.assert_equal(cmap.colors[1], np.array([0.1, 0.1, 0.1, 1.0]))
87+
88+
89+
def test_from_levels_and_cmap_color_list_explicit():
90+
91+
levels = [1, 2, 3, 4, 5]
92+
93+
# ensure colors are repeated (although that can also be unexpected)
94+
cmap, norm = mpu.from_levels_and_cmap(levels, ["b", "k"])
95+
96+
assert_cmap_norm(cmap, norm, levels, extend="neither")
97+
98+
np.testing.assert_equal(cmap.colors[0], np.array([0.0, 0.0, 1.0, 1.0])) # blue
99+
np.testing.assert_equal(cmap.colors[1], np.array([0.0, 0.0, 0.0, 1.0])) # black
100+
np.testing.assert_equal(cmap.colors[2], np.array([0.0, 0.0, 1.0, 1.0])) # blue
101+
np.testing.assert_equal(cmap.colors[3], np.array([0.0, 0.0, 0.0, 1.0])) # black

0 commit comments

Comments
 (0)