matplotlib icon indicating copy to clipboard operation
matplotlib copied to clipboard

[Bug]: Empty bars are styled incorrectly in legend

Open rongcuid opened this issue 1 year ago • 6 comments

Bug summary

When plotting multiple plots with specified colors, if plot data is empty, color parameter is ignored.

Code for reproduction

plt.figure()
plt.barh([], [], label="X", color="C0")
plt.barh([], [], label="Y", color="C1")
plt.legend()
plt.show()

Actual outcome

legend

Expected outcome

legend_expected

Additional information

No response

Operating system

No response

Matplotlib Version

3.8.2

Matplotlib Backend

No response

Python version

No response

Jupyter version

No response

Installation

None

rongcuid avatar Jan 11 '24 19:01 rongcuid

In fact, you don't need both X and Y, any single thing with non-C0 is not the right colour.

QuLogic avatar Jan 12 '24 00:01 QuLogic

The problem here is that bar[h] return a BarContainer which doesn't know anything about the inputs. The legend looks at the first patch for styling, and since there are none, it just returns the default style. All the input settings have been thrown away so there's no other way for it to figure it out.

As a workaround, it looks like you can pass a np.nan so that at least a Patch is created, but it won't be drawn:

plt.barh([np.nan], [np.nan], label="X", color="C1")

issue27638

QuLogic avatar Jan 12 '24 00:01 QuLogic

Can bar container record the style then? I suppose it's not hard to add.

rongcuid avatar Jan 12 '24 03:01 rongcuid

As a workaround, it looks like you can pass a np.nan so that at least a Patch is created, but it won't be drawn:

Would it make sense to do something like this (below) to always create a dummy patch if provided with an empty list or array? Or is this too hacky? It seems to solve this bug but I am not sure if it would change expected behavior too much.

_axes.py image Would obviously add an analog to the horizontal case too.

lcapalleja avatar Jan 30 '24 18:01 lcapalleja

Adding it to the container seems like a better option. If the user adds the np.nan they know, but if we start adding invisible artists that may break some users who are not expecting it...

tacaswell avatar Feb 01 '24 19:02 tacaswell

Related to https://github.com/matplotlib/matplotlib/issues/21506

oscargus avatar Feb 01 '24 22:02 oscargus

I'm going to close as a duplicate of #21506; @oscargus also has a PR at #22182, but it uses the np.nan approach, which seems disliked.

QuLogic avatar May 17 '24 21:05 QuLogic