Skip to content

Commit b18afbf

Browse files
authored
ListedColormap: don't pass N colors (#9811)
* ListedColormap: don't pass N colors * fix somewhere else * fix typing
1 parent 38d5308 commit b18afbf

File tree

2 files changed

+7
-5
lines changed

2 files changed

+7
-5
lines changed

xarray/plot/utils.py

+4-3
Original file line numberDiff line numberDiff line change
@@ -131,8 +131,9 @@ def _color_palette(cmap, n_colors):
131131

132132
colors_i = np.linspace(0, 1.0, n_colors)
133133
if isinstance(cmap, list | tuple):
134-
# we have a list of colors
135-
cmap = ListedColormap(cmap, N=n_colors)
134+
# expand or truncate the list of colors to n_colors
135+
cmap = list(itertools.islice(itertools.cycle(cmap), n_colors))
136+
cmap = ListedColormap(cmap)
136137
pal = cmap(colors_i)
137138
elif isinstance(cmap, str):
138139
# we have some sort of named palette
@@ -151,7 +152,7 @@ def _color_palette(cmap, n_colors):
151152
pal = sns.color_palette(cmap, n_colors=n_colors)
152153
except ValueError:
153154
# or maybe we just got a single color as a string
154-
cmap = ListedColormap([cmap], N=n_colors)
155+
cmap = ListedColormap([cmap] * n_colors)
155156
pal = cmap(colors_i)
156157
else:
157158
# cmap better be a LinearSegmentedColormap (e.g. viridis)

xarray/tests/test_plot.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -1805,8 +1805,9 @@ def test_colors_np_levels(self) -> None:
18051805
artist = self.darray.plot.contour(levels=levels, colors=["k", "r", "w", "b"])
18061806
cmap = artist.cmap
18071807
assert isinstance(cmap, mpl.colors.ListedColormap)
1808-
colors = cmap.colors
1809-
assert isinstance(colors, list)
1808+
# non-optimal typing in matplotlib (ArrayLike)
1809+
# https://github.com/matplotlib/matplotlib/blob/84464dd085210fb57cc2419f0d4c0235391d97e6/lib/matplotlib/colors.pyi#L133
1810+
colors = cast(np.ndarray, cmap.colors)
18101811

18111812
assert self._color_as_tuple(colors[1]) == (1.0, 0.0, 0.0)
18121813
assert self._color_as_tuple(colors[2]) == (1.0, 1.0, 1.0)

0 commit comments

Comments
 (0)