Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

ENH: Add support for per-label padding in bar_label #29696

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Mar 18, 2025
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions 5 doc/users/next_whats_new/bar_label_padding_update.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
Array-like padding accepted for ``bar_label``
--------------------------------------------------------------------------
``bar_label`` will now accept both a float value or an array-like object
for padding. If an array-like is provided, the padding values are applied
to each label individually. Must have the same length as container.
timhoffm marked this conversation as resolved.
Show resolved Hide resolved
22 changes: 17 additions & 5 deletions 22 lib/matplotlib/axes/_axes.py
Original file line number Diff line number Diff line change
Expand Up @@ -2884,8 +2884,10 @@
(useful for stacked bars, i.e.,
:doc:`/gallery/lines_bars_and_markers/bar_label_demo`)

padding : float, default: 0
padding : float or array-like, default: 0

Check warning on line 2887 in lib/matplotlib/axes/_axes.py

View check run for this annotation

Codecov / codecov/patch

lib/matplotlib/axes/_axes.py#L2887

Added line #L2887 was not covered by tests
Distance of label from the end of the bar, in points.
If an array-like is provided, the padding values are applied
to each label individually. Must have the same length as container.
timhoffm marked this conversation as resolved.
Show resolved Hide resolved

**kwargs
Any remaining keyword arguments are passed through to
Expand Down Expand Up @@ -2935,8 +2937,18 @@

annotations = []

for bar, err, dat, lbl in itertools.zip_longest(
bars, errs, datavalues, labels
if np.iterable(padding):
# if padding iterable, check length
padding = np.asarray(padding)
if len(padding) != len(bars):
raise ValueError(
f"padding must be of length {len(bars)} when passed as a sequence")
else:
# single value, apply to all labels
padding = [padding] * len(bars)

for bar, err, dat, lbl, pad in itertools.zip_longest(
bars, errs, datavalues, labels, padding
):
(x0, y0), (x1, y1) = bar.get_bbox().get_points()
xc, yc = (x0 + x1) / 2, (y0 + y1) / 2
Expand Down Expand Up @@ -2976,10 +2988,10 @@

if orientation == "vertical":
y_direction = -1 if y_inverted else 1
xytext = 0, y_direction * sign(dat) * padding
xytext = 0, y_direction * sign(dat) * pad
else: # horizontal
x_direction = -1 if x_inverted else 1
xytext = x_direction * sign(dat) * padding, 0
xytext = x_direction * sign(dat) * pad, 0

if label_type == "center":
ha, va = "center", "center"
Expand Down
2 changes: 1 addition & 1 deletion 2 lib/matplotlib/axes/_axes.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -268,7 +268,7 @@ class Axes(_AxesBase):
*,
fmt: str | Callable[[float], str] = ...,
label_type: Literal["center", "edge"] = ...,
padding: float = ...,
padding: float | ArrayLike = ...,
**kwargs
) -> list[Annotation]: ...
def broken_barh(
Expand Down
2 changes: 1 addition & 1 deletion 2 lib/matplotlib/pyplot.py
Original file line number Diff line number Diff line change
Expand Up @@ -3025,7 +3025,7 @@ def bar_label(
*,
fmt: str | Callable[[float], str] = "%g",
label_type: Literal["center", "edge"] = "edge",
padding: float = 0,
padding: float | ArrayLike = 0,
**kwargs,
) -> list[Annotation]:
return gca().bar_label(
Expand Down
17 changes: 17 additions & 0 deletions 17 lib/matplotlib/tests/test_axes.py
Original file line number Diff line number Diff line change
Expand Up @@ -8868,6 +8868,23 @@ def test_bar_label_nan_ydata_inverted():
assert labels[0].get_verticalalignment() == 'bottom'


def test_bar_label_padding():
"""Test that bar_label accepts both float and array-like padding."""
ax = plt.gca()
xs, heights = [1, 2], [3, 4]
rects = ax.bar(xs, heights)
labels1 = ax.bar_label(rects, padding=5) # test float value
assert labels1[0].xyann[1] == 5
assert labels1[1].xyann[1] == 5

labels2 = ax.bar_label(rects, padding=[2, 8]) # test array-like values
assert labels2[0].xyann[1] == 2
assert labels2[1].xyann[1] == 8

with pytest.raises(ValueError, match="padding must be of length"):
ax.bar_label(rects, padding=[1, 2, 3])


def test_nan_barlabels():
fig, ax = plt.subplots()
bars = ax.bar([1, 2, 3], [np.nan, 1, 2], yerr=[0.2, 0.4, 0.6])
Expand Down
Loading
Morty Proxy This is a proxified and sanitized view of the page, visit original site.