Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit eedbfbc

Browse files
authored
Merge pull request #20085 from meeseeksmachine/auto-backport-of-pr-20082-on-v3.4.x
Backport PR #20082 on branch v3.4.x (Fix bar_label for bars with nan values)
2 parents 962cf51 + b6ba8ce commit eedbfbc

File tree

2 files changed

+18
-8
lines changed

2 files changed

+18
-8
lines changed

lib/matplotlib/axes/_axes.py

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2624,14 +2624,15 @@ def sign(x):
26242624
if label_type == "center":
26252625
ha, va = "center", "center"
26262626
elif label_type == "edge":
2627-
if orientation == "vertical" and dat >= 0:
2628-
ha, va = "center", "bottom"
2629-
elif orientation == "vertical" and dat < 0:
2630-
ha, va = "center", "top"
2631-
elif orientation == "horizontal" and dat >= 0:
2632-
ha, va = "left", "center"
2633-
elif orientation == "horizontal" and dat < 0:
2634-
ha, va = "right", "center"
2627+
if orientation == "vertical":
2628+
ha = 'center'
2629+
va = 'top' if dat < 0 else 'bottom' # also handles NaN
2630+
elif orientation == "horizontal":
2631+
ha = 'right' if dat < 0 else 'left' # also handles NaN
2632+
va = 'center'
2633+
2634+
if np.isnan(dat):
2635+
lbl = ''
26352636

26362637
annotation = self.annotate(fmt % value if lbl is None else lbl,
26372638
xy, xytext, textcoords="offset points",

lib/matplotlib/tests/test_axes.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7004,6 +7004,15 @@ def test_bar_label_labels():
70047004
assert labels[1].get_text() == 'B'
70057005

70067006

7007+
def test_bar_label_nan_ydata():
7008+
ax = plt.gca()
7009+
bars = ax.bar([2, 3], [np.nan, 1])
7010+
labels = ax.bar_label(bars)
7011+
assert [l.get_text() for l in labels] == ['', '1']
7012+
assert labels[0].xy == (2, 0)
7013+
assert labels[0].get_va() == 'bottom'
7014+
7015+
70077016
def test_patch_bounds(): # PR 19078
70087017
fig, ax = plt.subplots()
70097018
ax.add_patch(mpatches.Wedge((0, -1), 1.05, 60, 120, 0.1))

0 commit comments

Comments
 (0)