From 4e6732661670cdeec352cf68edff5653dfbf1f64 Mon Sep 17 00:00:00 2001 From: Tim Hoffmann <2836374+timhoffm@users.noreply.github.com> Date: Thu, 4 Jun 2026 21:56:25 +0200 Subject: [PATCH] Backport PR #31819: FIX: use data values in bar_label --- lib/matplotlib/axes/_axes.py | 11 ++--------- lib/matplotlib/tests/test_axes.py | 9 ++++++++- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/lib/matplotlib/axes/_axes.py b/lib/matplotlib/axes/_axes.py index 244aab09551b..0eca86a38b01 100644 --- a/lib/matplotlib/axes/_axes.py +++ b/lib/matplotlib/axes/_axes.py @@ -2907,10 +2907,8 @@ def sign(x): if orientation == "vertical": extrema = max(y0, y1) if dat >= 0 else min(y0, y1) - length = abs(y0 - y1) else: # horizontal extrema = max(x0, x1) if dat >= 0 else min(x0, x1) - length = abs(x0 - x1) if err is None or np.size(err) == 0: endpt = extrema @@ -2919,11 +2917,6 @@ def sign(x): else: # horizontal endpt = err[:, 0].max() if dat >= 0 else err[:, 0].min() - if label_type == "center": - value = sign(dat) * length - else: # edge - value = extrema - if label_type == "center": xy = (0.5, 0.5) kwargs["xycoords"] = ( @@ -2966,9 +2959,9 @@ def sign(x): if lbl is None: if isinstance(fmt, str): - lbl = cbook._auto_format_str(fmt, value) + lbl = cbook._auto_format_str(fmt, dat) elif callable(fmt): - lbl = fmt(value) + lbl = fmt(dat) else: raise TypeError("fmt must be a str or callable") annotation = self.annotate(lbl, diff --git a/lib/matplotlib/tests/test_axes.py b/lib/matplotlib/tests/test_axes.py index 0f7f8e37add0..a118d2f27353 100644 --- a/lib/matplotlib/tests/test_axes.py +++ b/lib/matplotlib/tests/test_axes.py @@ -13,7 +13,7 @@ from types import SimpleNamespace import unittest.mock -import dateutil.tz +import dateutil import numpy as np from numpy import ma @@ -9459,6 +9459,13 @@ def test_nan_barlabels(): assert np.allclose(ax.get_ylim(), (0.0, 3.0)) +def test_int_fmt_bar_label(): + fig, ax = plt.subplots() + bars = ax.bar(['foo', 'bar'], [5, 7]) + labels = ax.bar_label(bars, fmt='{:d}') + assert [l.get_text() for l in labels] == ['5', '7'] + + def test_patch_bounds(): # PR 19078 fig, ax = plt.subplots() ax.add_patch(mpatches.Wedge((0, -1), 1.05, 60, 120, width=0.1))