[Bug]: Empty bars are styled incorrectly in legend
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
Expected outcome
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
In fact, you don't need both X and Y, any single thing with non-C0 is not the right colour.
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")
Can bar container record the style then? I suppose it's not hard to add.
As a workaround, it looks like you can pass a
np.nanso that at least aPatchis 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
Would obviously add an analog to the horizontal case too.
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...
Related to https://github.com/matplotlib/matplotlib/issues/21506
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.