Skip to content

Commit 7d0030c

Browse files
authored
Merge pull request matplotlib#23698 from stefmolin/bar-label-center
Fix bug in `Axes.bar_label(label_type='center')` for non-linear scales.
2 parents 158f8ca + 5ffb34e commit 7d0030c

File tree

3 files changed

+185
-3
lines changed

3 files changed

+185
-3
lines changed

lib/matplotlib/axes/_axes.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2715,7 +2715,13 @@ def sign(x):
27152715
value = extrema
27162716

27172717
if label_type == "center":
2718-
xy = xc, yc
2718+
xy = (0.5, 0.5)
2719+
kwargs["xycoords"] = (
2720+
lambda r, b=bar:
2721+
mtransforms.Bbox.intersection(
2722+
b.get_window_extent(r), b.get_clip_box()
2723+
)
2724+
)
27192725
else: # edge
27202726
if orientation == "vertical":
27212727
xy = xc, endpt
Lines changed: 166 additions & 0 deletions
Loading

lib/matplotlib/tests/test_axes.py

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7792,14 +7792,24 @@ def test_bar_label_location_center():
77927792
ys, widths = [1, 2], [3, -4]
77937793
rects = ax.barh(ys, widths)
77947794
labels = ax.bar_label(rects, label_type='center')
7795-
assert labels[0].xy == (widths[0] / 2, ys[0])
7795+
assert labels[0].xy == (0.5, 0.5)
77967796
assert labels[0].get_ha() == 'center'
77977797
assert labels[0].get_va() == 'center'
7798-
assert labels[1].xy == (widths[1] / 2, ys[1])
7798+
assert labels[1].xy == (0.5, 0.5)
77997799
assert labels[1].get_ha() == 'center'
78007800
assert labels[1].get_va() == 'center'
78017801

78027802

7803+
@image_comparison(['test_centered_bar_label_nonlinear.svg'])
7804+
def test_centered_bar_label_nonlinear():
7805+
_, ax = plt.subplots()
7806+
bar_container = ax.barh(['c', 'b', 'a'], [1_000, 5_000, 7_000])
7807+
ax.set_xscale('log')
7808+
ax.set_xlim(1, None)
7809+
ax.bar_label(bar_container, label_type='center')
7810+
ax.set_axis_off()
7811+
7812+
78037813
def test_bar_label_location_errorbars():
78047814
ax = plt.gca()
78057815
xs, heights = [1, 2], [3, -4]

0 commit comments

Comments
 (0)