From de3e7da94814888fccb2fd5dab1f20963911135c Mon Sep 17 00:00:00 2001 From: m-sahare Date: Mon, 20 Apr 2026 15:14:45 +0530 Subject: [PATCH] Fix contour behavior when Z is constant (zmin == zmax) --- lib/matplotlib/contour.py | 13 +++++++++++-- lib/matplotlib/tests/test_contour.py | 13 +++++++++++++ 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/lib/matplotlib/contour.py b/lib/matplotlib/contour.py index eb103dc2fc2a..aa2fb35a2750 100644 --- a/lib/matplotlib/contour.py +++ b/lib/matplotlib/contour.py @@ -6,7 +6,7 @@ import functools import math from numbers import Integral - +import warnings import numpy as np from numpy import ma @@ -998,6 +998,15 @@ def _autolev(self): one contour line, but two filled regions, and therefore three levels to provide boundaries for both regions. """ + + + if self.zmin == self.zmax: + warnings.warn( + "Z is constant; contour levels are not meaningful.", + stacklevel=2 + ) + return np.array([self.zmin]) + lev = self.locator.tick_values(self.zmin, self.zmax) try: @@ -1006,7 +1015,7 @@ def _autolev(self): except AttributeError: pass - # Trim excess levels the locator may have supplied. + # Trim excess levels the locator may have supplied. under = np.nonzero(lev < self.zmin)[0] i0 = under[-1] if len(under) else 0 over = np.nonzero(lev > self.zmax)[0] diff --git a/lib/matplotlib/tests/test_contour.py b/lib/matplotlib/tests/test_contour.py index 42ad75862b2e..2c7af84f03c1 100644 --- a/lib/matplotlib/tests/test_contour.py +++ b/lib/matplotlib/tests/test_contour.py @@ -876,3 +876,16 @@ def test_contour_aliases(fig_test, fig_ref): def test_contour_singular_color(): with pytest.raises(TypeError): plt.figure().add_subplot().contour([[0, 1], [2, 3]], color="r") + +def test_contour_constant_z_warns_and_single_level(): + Z = np.ones((10, 10)) + + fig, ax = plt.subplots() + + # Expect a warning + with pytest.warns(UserWarning, match="Z is constant"): + cs = ax.contour(Z) + + # Ensure only one level is created + assert len(cs.levels) == 1 + assert cs.levels[0] == 1.0 \ No newline at end of file