Skip to content

bar_label fails with nan data values #20058

Closed
@mwaskom

Description

@mwaskom

Bug report

Bug summary

ax.bar_label is not robust to bars with missing (nan) data values.

The problem is in here:

if label_type == "center":
ha, va = "center", "center"
elif label_type == "edge":
if orientation == "vertical" and dat >= 0:
ha, va = "center", "bottom"
elif orientation == "vertical" and dat < 0:
ha, va = "center", "top"
elif orientation == "horizontal" and dat >= 0:
ha, va = "left", "center"
elif orientation == "horizontal" and dat < 0:
ha, va = "right", "center"

Because nan is neither greater than nor less than 0, ha and va never get defined, and don't have default values.

Code for reproduction

ax = plt.gca()
bars = ax.bar([0, 1], [np.nan, 1])
ax.bar_label(bars)

Actual outcome

---------------------------------------------------------------------------
UnboundLocalError                         Traceback (most recent call last)
<ipython-input-65-f996ada4311b> in <module>
      1 ax = plt.gca()
      2 bars = ax.bar([0, 1], [np.nan, 1])
----> 3 ax.bar_label(bars)

~/miniconda3/envs/py39/lib/python3.9/site-packages/matplotlib/axes/_axes.py in bar_label(self, container, labels, fmt, label_type, padding, **kwargs)
   2636             annotation = self.annotate(fmt % value if lbl is None else lbl,
   2637                                        xy, xytext, textcoords="offset points",
-> 2638                                        ha=ha, va=va, **kwargs)
   2639             annotations.append(annotation)
   2640 

UnboundLocalError: local variable 'ha' referenced before assignment

Expected outcome

No error; no annotation generated. (Or maybe empty string?)

Matplotlib version

  • Operating system: macos
  • Matplotlib version (import matplotlib; print(matplotlib.__version__)): 3.4.1
  • Matplotlib backend (print(matplotlib.get_backend())): pylab inline
  • Python version: 3.9

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions