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

Skip to content

Commit 08044f7

Browse files
authored
Merge pull request #20082 from timhoffm/fix-bar_label-nan
Fix bar_label for bars with nan values
2 parents 8ce1e02 + 5cf3fbe commit 08044f7

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
@@ -2625,14 +2625,15 @@ def sign(x):
26252625
if label_type == "center":
26262626
ha, va = "center", "center"
26272627
elif label_type == "edge":
2628-
if orientation == "vertical" and dat >= 0:
2629-
ha, va = "center", "bottom"
2630-
elif orientation == "vertical" and dat < 0:
2631-
ha, va = "center", "top"
2632-
elif orientation == "horizontal" and dat >= 0:
2633-
ha, va = "left", "center"
2634-
elif orientation == "horizontal" and dat < 0:
2635-
ha, va = "right", "center"
2628+
if orientation == "vertical":
2629+
ha = 'center'
2630+
va = 'top' if dat < 0 else 'bottom' # also handles NaN
2631+
elif orientation == "horizontal":
2632+
ha = 'right' if dat < 0 else 'left' # also handles NaN
2633+
va = 'center'
2634+
2635+
if np.isnan(dat):
2636+
lbl = ''
26362637

26372638
annotation = self.annotate(fmt % value if lbl is None else lbl,
26382639
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
@@ -7027,6 +7027,15 @@ def test_bar_label_labels():
70277027
assert labels[1].get_text() == 'B'
70287028

70297029

7030+
def test_bar_label_nan_ydata():
7031+
ax = plt.gca()
7032+
bars = ax.bar([2, 3], [np.nan, 1])
7033+
labels = ax.bar_label(bars)
7034+
assert [l.get_text() for l in labels] == ['', '1']
7035+
assert labels[0].xy == (2, 0)
7036+
assert labels[0].get_va() == 'bottom'
7037+
7038+
70307039
def test_patch_bounds(): # PR 19078
70317040
fig, ax = plt.subplots()
70327041
ax.add_patch(mpatches.Wedge((0, -1), 1.05, 60, 120, 0.1))

0 commit comments

Comments
 (0)