diff --git a/lib/matplotlib/tests/test_ticker.py b/lib/matplotlib/tests/test_ticker.py index 263df149de5d..611b5cf968d8 100644 --- a/lib/matplotlib/tests/test_ticker.py +++ b/lib/matplotlib/tests/test_ticker.py @@ -510,6 +510,14 @@ class TestScalarFormatter: (True, (6, 6), (-1e5, 1e5), 6, False), ] + cursor_data = [ + [0., "0.000"], + [0.0123, "0.012"], + [0.123, "0.123"], + [1.23, "1.230"], + [12.3, "12.300"], + ] + @pytest.mark.parametrize('unicode_minus, result', [(True, "\N{MINUS SIGN}1"), (False, "-1")]) def test_unicode_minus(self, unicode_minus, result): @@ -556,15 +564,21 @@ def test_scilimits(self, sci_type, scilimits, lim, orderOfMag, fewticks): tmp_form.set_locs(ax.yaxis.get_majorticklocs()) assert orderOfMag == tmp_form.orderOfMagnitude - def test_cursor_precision(self): + @pytest.mark.parametrize('data, expected', cursor_data) + def test_cursor_precision(self, data, expected): fig, ax = plt.subplots() ax.set_xlim(-1, 1) # Pointing precision of 0.001. fmt = ax.xaxis.get_major_formatter().format_data_short - assert fmt(0.) == "0.000" - assert fmt(0.0123) == "0.012" - assert fmt(0.123) == "0.123" - assert fmt(1.23) == "1.230" - assert fmt(12.3) == "12.300" + assert fmt(data) == expected + + @pytest.mark.parametrize('data, expected', cursor_data) + def test_cursor_dummy_axis(self, data, expected): + # Issue #17624 + sf = mticker.ScalarFormatter() + sf.create_dummy_axis() + sf.set_bounds(0, 10) + fmt = sf.format_data_short + assert fmt(data) == expected class FakeAxis: diff --git a/lib/matplotlib/ticker.py b/lib/matplotlib/ticker.py index 31dbf601e531..6c288b6c9144 100644 --- a/lib/matplotlib/ticker.py +++ b/lib/matplotlib/ticker.py @@ -198,6 +198,8 @@ class _DummyAxis: + __name__ = "dummy" + def __init__(self, minpos=0): self.dataLim = mtransforms.Bbox.unit() self.viewLim = mtransforms.Bbox.unit() @@ -693,7 +695,7 @@ def format_data_short(self, value): if isinstance(value, Integral): fmt = "%d" else: - if self.axis.__name__ in ["xaxis", "yaxis"]: + if getattr(self.axis, "__name__", "") in ["xaxis", "yaxis"]: if self.axis.__name__ == "xaxis": axis_trf = self.axis.axes.get_xaxis_transform() axis_inv_trf = axis_trf.inverted() @@ -708,8 +710,8 @@ def format_data_short(self, value): screen_xy + [[0, -1], [0, +1]])[:, 1] delta = abs(neighbor_values - value).max() else: - # Rough approximation: no more than 1e4 pixels. - delta = self.axis.get_view_interval() / 1e4 + # Rough approximation: no more than 1e4 divisions. + delta = np.diff(self.axis.get_view_interval()) / 1e4 # If e.g. value = 45.67 and delta = 0.02, then we want to round to # 2 digits after the decimal point (floor(log10(0.02)) = -2); # 45.67 contributes 2 digits before the decimal point