Skip to content

Handle single color in ContourSet #28786

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Sep 14, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions doc/users/next_whats_new/contour_color.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
Specifying a single color in ``contour`` and ``contourf``
---------------------------------------------------------

`~.Axes.contour` and `~.Axes.contourf` previously accepted a single color
provided it was expressed as a string. This restriction has now been removed
and a single color in any format described in the :ref:`colors_def` tutorial
may be passed.

.. plot::
:include-source: true
:alt: Two-panel example contour plots. The left panel has all transparent red contours. The right panel has all dark blue contours.

import matplotlib.pyplot as plt

fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(6, 3))
z = [[0, 1], [1, 2]]

ax1.contour(z, colors=('r', 0.4))
ax2.contour(z, colors=(0.1, 0.2, 0.5))

plt.show()
27 changes: 17 additions & 10 deletions lib/matplotlib/contour.py
Original file line number Diff line number Diff line change
Expand Up @@ -702,6 +702,11 @@ def __init__(self, ax, *args,
self._extend_min = self.extend in ['min', 'both']
self._extend_max = self.extend in ['max', 'both']
if self.colors is not None:
if mcolors.is_color_like(self.colors):
color_sequence = [self.colors]
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍 for using a new name and not modifying colors. This makes it clear it's a local name and prevents users from thinking its the argument colors, which also gets stored as self.colors.

else:
color_sequence = self.colors

ncolors = len(self.levels)
if self.filled:
ncolors -= 1
Expand All @@ -718,19 +723,19 @@ def __init__(self, ax, *args,
total_levels = (ncolors +
int(self._extend_min) +
int(self._extend_max))
if (len(self.colors) == total_levels and
if (len(color_sequence) == total_levels and
(self._extend_min or self._extend_max)):
use_set_under_over = True
if self._extend_min:
i0 = 1

cmap = mcolors.ListedColormap(self.colors[i0:None], N=ncolors)
cmap = mcolors.ListedColormap(color_sequence[i0:None], N=ncolors)

if use_set_under_over:
if self._extend_min:
cmap.set_under(self.colors[0])
cmap.set_under(color_sequence[0])
if self._extend_max:
cmap.set_over(self.colors[-1])
cmap.set_over(color_sequence[-1])

# label lists must be initialized here
self.labelTexts = []
Expand Down Expand Up @@ -1498,10 +1503,12 @@ def _initialize_x_y(self, z):
The sequence is cycled for the levels in ascending order. If the
sequence is shorter than the number of levels, it's repeated.

As a shortcut, single color strings may be used in place of
one-element lists, i.e. ``'red'`` instead of ``['red']`` to color
all levels with the same color. This shortcut does only work for
color strings, not for other ways of specifying colors.
As a shortcut, a single color may be used in place of one-element lists, i.e.
``'red'`` instead of ``['red']`` to color all levels with the same color.

.. versionchanged:: 3.10
Previously a single color had to be expressed as a string, but now any
valid color format may be passed.

By default (value *None*), the colormap specified by *cmap*
will be used.
Expand Down Expand Up @@ -1569,10 +1576,10 @@ def _initialize_x_y(self, z):

An existing `.QuadContourSet` does not get notified if
properties of its colormap are changed. Therefore, an explicit
call `.QuadContourSet.changed()` is needed after modifying the
call ``QuadContourSet.changed()`` is needed after modifying the
colormap. The explicit call can be left out, if a colorbar is
assigned to the `.QuadContourSet` because it internally calls
`.QuadContourSet.changed()`.
``QuadContourSet.changed()``.

Example::

Expand Down
14 changes: 14 additions & 0 deletions lib/matplotlib/tests/test_contour.py
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,20 @@ def test_given_colors_levels_and_extends():
plt.colorbar(c, ax=ax)


@pytest.mark.parametrize('color, extend', [('darkred', 'neither'),
('darkred', 'both'),
(('r', 0.5), 'neither'),
((0.1, 0.2, 0.5, 0.3), 'neither')])
def test_single_color_and_extend(color, extend):
z = [[0, 1], [1, 2]]

_, ax = plt.subplots()
levels = [0.5, 0.75, 1, 1.25, 1.5]
cs = ax.contour(z, levels=levels, colors=color, extend=extend)
for c in cs.get_edgecolors():
assert same_color(c, color)


@image_comparison(['contour_log_locator.svg'], style='mpl20', remove_text=False)
def test_log_locator_levels():

Expand Down
Loading