Skip to content

[Bug]: bar_label fails with nan errorbar values #22910

Closed
@meluso

Description

@meluso

Bug summary

ax.bar_label appears not to be robust to bars with missing (nan) values when also including error values. This issue is similar to #20058, but occurs in each of three cases:

Case 1. When a dependent value is missing.
Case 2. When an error value is missing.
Case 3. When both a dependent value and an error value are missing.

The error seems to happen here, but I don't know the code well enough to pinpoint what should change to fix this:

if err is None:
endpt = extrema
elif orientation == "vertical":
endpt = err[:, 1].max() if dat >= 0 else err[:, 1].min()
elif orientation == "horizontal":
endpt = err[:, 0].max() if dat >= 0 else err[:, 0].min()

Code for reproduction

#%% Case 1: Missing dependent value
import matplotlib.pyplot as plt
import numpy as np
ax = plt.gca()
bars = ax.bar([0, 1, 2], [np.nan, 0.3, 0.4], yerr=[1, 0.1, 0.1])
ax.bar_label(bars)

#%% Case 2: Missing error value
import matplotlib.pyplot as plt
import numpy as np
ax = plt.gca()
bars = ax.bar([0, 1, 2], [0, 0.3, 0.4], yerr=[np.nan, 0.1, 0.1])
ax.bar_label(bars)

#%% Case 3: Missing dependent and error values
import matplotlib.pyplot as plt
import numpy as np
ax = plt.gca()
bars = ax.bar([0, 1, 2], [np.nan, 0.3, 0.4], yerr=[np.nan, 0.1, 0.1])
ax.bar_label(bars)

Actual outcome

runcell('Case 3: Missing dependent and error values', 'C:/Users/jam/Documents/GitHub/ci-greedy-agents-base/untitled2.py')
Traceback (most recent call last):

File "C:\ProgramData\Miniconda3\lib\site-packages\spyder_kernels\py3compat.py", line 356, in compat_exec
exec(code, globals, locals)

File "c:\users\jam\documents\github\ci-greedy-agents-base\untitled2.py", line 27, in
ax.bar_label(bars)

File "C:\ProgramData\Miniconda3\lib\site-packages\matplotlib\axes_axes.py", line 2641, in bar_label
endpt = err[:, 1].max() if dat >= 0 else err[:, 1].min()

IndexError: too many indices for array: array is 1-dimensional, but 2 were indexed

Expected outcome

Maybe either raise an error telling me what I should do instead, or have the code resolve whatever the source is on the backend? Ideally, I think the following should happen:

Case 1. Raise an error that there is no value to apply the errorbar value to.
Cases 2 & 3. Ignore the missing value and move on to the next.

Additional information

No response

Operating system

Windows 10.1

Matplotlib Version

3.5.1

Matplotlib Backend

module://matplotlib_inline.backend_inline

Python version

3.9.5

Jupyter version

Spyder 5.3.0

Installation

conda

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions