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

Skip to content

Commit 6ac197f

Browse files
committed
BUG: handle empty levels array in contour, closes #7486
This relates to line contours only, not to filled contours. This handles the case where an empty array is provided as the "levels" kwarg, or where for any reason there are no levels within the data range. An example is the case of uniform z. The levels array is then set to the minimum value of z so that the plotting can proceed, and a warning is generated.
1 parent eb6e422 commit 6ac197f

2 files changed

Lines changed: 36 additions & 7 deletions

File tree

lib/matplotlib/contour.py

Lines changed: 14 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1132,14 +1132,10 @@ def _autolev(self, N):
11321132
self.locator = ticker.LogLocator()
11331133
else:
11341134
self.locator = ticker.MaxNLocator(N + 1, min_n_ticks=1)
1135-
zmax = self.zmax
1136-
zmin = self.zmin
1137-
lev = self.locator.tick_values(zmin, zmax)
1135+
1136+
lev = self.locator.tick_values(self.zmin, self.zmax)
11381137
self._auto = True
1139-
if self.filled:
1140-
return lev
1141-
# For line contours, drop levels outside the data range.
1142-
return lev[(lev > zmin) & (lev < zmax)]
1138+
return lev
11431139

11441140
def _contour_level_args(self, z, args):
11451141
"""
@@ -1165,6 +1161,17 @@ def _contour_level_args(self, z, args):
11651161
"Last {0} arg must give levels; see help({0})"
11661162
.format(fn))
11671163
self.levels = lev
1164+
else:
1165+
self.levels = np.asarray(self.levels).astype(np.float64)
1166+
1167+
if not self.filled:
1168+
inside = (self.levels > self.zmin) & (self.levels < self.zmax)
1169+
self.levels = self.levels[inside]
1170+
if len(self.levels) == 0:
1171+
self.levels = [self.zmin]
1172+
warnings.warn("No contour levels were found"
1173+
" within the data range.")
1174+
11681175
if self.filled and len(self.levels) < 2:
11691176
raise ValueError("Filled contours require at least 2 levels.")
11701177

lib/matplotlib/tests/test_contour.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -132,6 +132,28 @@ def test_contour_shape_invalid_2():
132132
excinfo.match(r'Input z must be a 2D array.')
133133

134134

135+
def test_contour_empty_levels():
136+
137+
x = np.arange(9)
138+
z = np.random.random((9, 9))
139+
140+
fig, ax = plt.subplots()
141+
with pytest.warns(UserWarning) as record:
142+
ax.contour(x, x, z, levels=[])
143+
assert len(record) == 1
144+
145+
146+
def test_contour_uniform_z():
147+
148+
x = np.arange(9)
149+
z = np.ones((9, 9))
150+
151+
fig, ax = plt.subplots()
152+
with pytest.warns(UserWarning) as record:
153+
ax.contour(x, x, z)
154+
assert len(record) == 1
155+
156+
135157
@image_comparison(baseline_images=['contour_manual_labels'])
136158
def test_contour_manual_labels():
137159

0 commit comments

Comments
 (0)