diff --git a/lib/matplotlib/axis.py b/lib/matplotlib/axis.py index e80e49e53bb9..eb0c00801d7b 100644 --- a/lib/matplotlib/axis.py +++ b/lib/matplotlib/axis.py @@ -1825,8 +1825,11 @@ def set_ticklabels(self, ticklabels, *, minor=False, **kwargs): For each tick, includes ``tick.label1`` if it is visible, then ``tick.label2`` if it is visible, in that order. """ - ticklabels = [t.get_text() if hasattr(t, 'get_text') else t - for t in ticklabels] + try: + ticklabels = [t.get_text() if hasattr(t, 'get_text') else t + for t in ticklabels] + except TypeError: + raise TypeError(f"{ticklabels:=} must be a sequence") from None locator = (self.get_minor_locator() if minor else self.get_major_locator()) if isinstance(locator, mticker.FixedLocator): diff --git a/lib/matplotlib/tests/test_axes.py b/lib/matplotlib/tests/test_axes.py index a5f5ddad93c4..59ce45b107d4 100644 --- a/lib/matplotlib/tests/test_axes.py +++ b/lib/matplotlib/tests/test_axes.py @@ -5388,6 +5388,15 @@ def test_set_ticks_with_labels(fig_test, fig_ref): ax.set_yticks([2, 4], ['A', 'B'], minor=True) +def test_set_noniterable_ticklabels(): + # Ensure a useful TypeError message is raised + # when given a non-iterable ticklabels argument + # Pull request #22710 + with pytest.raises(TypeError, match='must be a sequence'): + fig, ax = plt.subplots(2) + ax[1].set_xticks([2, 9], 3.1) + + def test_subsampled_ticklabels(): # test issue 11937 fig, ax = plt.subplots()