Skip to content

Commit 12ce07f

Browse files
committed
Fix specifying number of levels with log contour
1 parent 192e935 commit 12ce07f

File tree

3 files changed

+25
-2
lines changed

3 files changed

+25
-2
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
Maximum levels on log-scaled contour plots are now respected
2+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3+
When plotting contours with a log norm, passing an integer value to the ``levels``
4+
argument to cap the maximum number of contour levels now works as intended.

lib/matplotlib/contour.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -969,7 +969,8 @@ def _autolev(self, N):
969969
Select contour levels to span the data.
970970
971971
The target number of levels, *N*, is used only when the
972-
scale is not log and default locator is used.
972+
locator is not set and the scale is log or the default
973+
locator is used.
973974
974975
We need two more levels for filled contours than for
975976
line contours, because for the latter we need to specify
@@ -980,7 +981,7 @@ def _autolev(self, N):
980981
"""
981982
if self.locator is None:
982983
if self.logscale:
983-
self.locator = ticker.LogLocator()
984+
self.locator = ticker.LogLocator(numticks=N)
984985
else:
985986
self.locator = ticker.MaxNLocator(N + 1, min_n_ticks=1)
986987

lib/matplotlib/tests/test_contour.py

+18
Original file line numberDiff line numberDiff line change
@@ -214,6 +214,24 @@ def test_log_locator_levels():
214214
assert_array_almost_equal(cb.ax.get_yticks(), c.levels)
215215

216216

217+
218+
@pytest.mark.parametrize("n_levels", [2, 3, 4, 5, 6])
219+
def test_lognorm_levels(n_levels):
220+
x = np.arange(100) + 1
221+
y = np.arange(100) + 1
222+
x, y = np.meshgrid(x, y)
223+
data = x**2 + y**2
224+
225+
fig, ax = plt.subplots()
226+
im = ax.contour(x, y, data, norm=LogNorm(), levels=n_levels)
227+
cbar = fig.colorbar(im, ax=ax)
228+
229+
levels = im.levels
230+
visible_levels = levels[(levels <= data.max()) & (levels >= data.min())]
231+
# levels parameter promises "no more than n+1 "nice" contour levels "
232+
assert len(visible_levels) <= n_levels + 1
233+
234+
217235
@image_comparison(['contour_datetime_axis.png'], style='mpl20')
218236
def test_contour_datetime_axis():
219237
fig = plt.figure()

0 commit comments

Comments
 (0)