Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit de3e7da

Browse files
committed
Fix contour behavior when Z is constant (zmin == zmax)
1 parent d84c7ee commit de3e7da

2 files changed

Lines changed: 24 additions & 2 deletions

File tree

lib/matplotlib/contour.py

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
import functools
77
import math
88
from numbers import Integral
9-
9+
import warnings
1010
import numpy as np
1111
from numpy import ma
1212

@@ -998,6 +998,15 @@ def _autolev(self):
998998
one contour line, but two filled regions, and therefore
999999
three levels to provide boundaries for both regions.
10001000
"""
1001+
1002+
1003+
if self.zmin == self.zmax:
1004+
warnings.warn(
1005+
"Z is constant; contour levels are not meaningful.",
1006+
stacklevel=2
1007+
)
1008+
return np.array([self.zmin])
1009+
10011010
lev = self.locator.tick_values(self.zmin, self.zmax)
10021011

10031012
try:
@@ -1006,7 +1015,7 @@ def _autolev(self):
10061015
except AttributeError:
10071016
pass
10081017

1009-
# Trim excess levels the locator may have supplied.
1018+
# Trim excess levels the locator may have supplied.
10101019
under = np.nonzero(lev < self.zmin)[0]
10111020
i0 = under[-1] if len(under) else 0
10121021
over = np.nonzero(lev > self.zmax)[0]

lib/matplotlib/tests/test_contour.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -876,3 +876,16 @@ def test_contour_aliases(fig_test, fig_ref):
876876
def test_contour_singular_color():
877877
with pytest.raises(TypeError):
878878
plt.figure().add_subplot().contour([[0, 1], [2, 3]], color="r")
879+
880+
def test_contour_constant_z_warns_and_single_level():
881+
Z = np.ones((10, 10))
882+
883+
fig, ax = plt.subplots()
884+
885+
# Expect a warning
886+
with pytest.warns(UserWarning, match="Z is constant"):
887+
cs = ax.contour(Z)
888+
889+
# Ensure only one level is created
890+
assert len(cs.levels) == 1
891+
assert cs.levels[0] == 1.0

0 commit comments

Comments
 (0)