Skip to content

Commit 256882f

Browse files
committed
added test for set_clim() callback count
1 parent e49d05a commit 256882f

2 files changed

Lines changed: 27 additions & 2 deletions

File tree

‎lib/matplotlib/colorizer.py‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -269,6 +269,8 @@ def set_clim(self, vmin=None, vmax=None):
269269
except (TypeError, ValueError):
270270
pass
271271

272+
orig_vmin_vmax = self.norm.vmin, self.norm.vmax
273+
272274
# Blocked context manager prevents callbacks from being triggered
273275
# until both vmin and vmax are updated
274276
with self.norm.callbacks.blocked(signal='changed'):
@@ -277,8 +279,9 @@ def set_clim(self, vmin=None, vmax=None):
277279
if vmax is not None:
278280
self.norm.vmax = colors._sanitize_extrema(vmax)
279281

280-
# self.changed() will now emit a update signal after both the limits are set
281-
self.changed()
282+
# self.changed() will now emit a update signal if the limits are changed
283+
if orig_vmin_vmax != (self.norm.vmin, self.norm.vmax):
284+
self.changed()
282285

283286
def get_clim(self):
284287
"""

‎lib/matplotlib/tests/test_colorbar.py‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,8 @@
1818
from matplotlib.ticker import FixedLocator, LogFormatter, StrMethodFormatter
1919
from matplotlib.testing.decorators import check_figures_equal
2020

21+
import unittest.mock
22+
2123

2224
def _get_cmap_norms():
2325
"""
@@ -660,6 +662,26 @@ def test_colorbar_scale_reset():
660662
assert pcm.norm.vmax == z.max()
661663

662664

665+
def test_set_clim_emits_single_callback():
666+
data = np.array([[1, 2], [3, 4]])
667+
fig, ax = plt.subplots()
668+
image = ax.imshow(data, cmap='viridis')
669+
670+
callback = unittest.mock.Mock()
671+
image.norm.callbacks.connect('changed', callback)
672+
673+
# Initial callback count should be zero
674+
assert callback.call_count == 0
675+
676+
# Call set_clim() to update the limits
677+
image.set_clim(1, 5)
678+
679+
# Assert that only one "changed" callback is sent after calling set_clim()
680+
callback.assert_called_once()
681+
682+
plt.close(fig)
683+
684+
663685
def test_colorbar_get_ticks_2():
664686
plt.rcParams['_internal.classic_mode'] = False
665687
fig, ax = plt.subplots()

0 commit comments

Comments
 (0)