Skip to content

[Bug]: Legend kwarg labelcolor='linecolor' not working properly when facecolor is 'None'  #30298

Open
@lukashergt

Description

@lukashergt

Bug summary

The legend kwarg labelcolor='linecolor' does not play nicely with histtype='step' histograms or with fc='None' scatter plots, resulting in an invisible legend label for the histogram, and in an IndexError for the scatter plot.

Code for reproduction

import numpy as np
import matplotlib.pyplot as plt
plt.rcParams['figure.figsize'] = (5, 5)
plt.rcParams['legend.loc'] = 1
plt.rcParams['legend.framealpha'] = 1

x, y = np.random.randn(2, 1000)

fig, axes = plt.subplots(2, 2, sharex=True, sharey='row')
axes[0, 0].hist(x, histtype='bar', label="spam")
axes[0, 1].hist(x, histtype='step', label="spam")
axes[1, 0].scatter(x, y, label="spam")
axes[1, 1].scatter(x, y, ec='C0', fc='None', label="spam")
for ax in axes.ravel():
    ax.legend(labelcolor='linecolor')

Actual outcome

Image

Note:

  • correctly coloured legend labels in both left panels
  • invisible legend label in the top right panel
  • no legend for the bottom right panel, instead the following error message:
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
Cell In[1], line 15
     13 axes[1, 1].scatter(x, y, ec='C0', fc='None', label="spam")
     14 for ax in axes.ravel():
---> 15     ax.legend(labelcolor='linecolor')

File [~/.virtualenv/py3121env/lib/python3.12/site-packages/matplotlib/axes/_axes.py:337](http://localhost:8888/home/lukas/.virtualenv/py3121env/lib/python3.12/site-packages/matplotlib/axes/_axes.py#line=336), in Axes.legend(self, *args, **kwargs)
    220 """
    221 Place a legend on the Axes.
    222 
   (...)    334 .. plot:: gallery[/text_labels_and_annotations/legend.py](http://localhost:8888/text_labels_and_annotations/legend.py)
    335 """
    336 handles, labels, kwargs = mlegend._parse_legend_args([self], *args, **kwargs)
--> 337 self.legend_ = mlegend.Legend(self, handles, labels, **kwargs)
    338 self.legend_._remove_method = self._remove_legend
    339 return self.legend_

File [~/.virtualenv/py3121env/lib/python3.12/site-packages/matplotlib/legend.py:601](http://localhost:8888/home/lukas/.virtualenv/py3121env/lib/python3.12/site-packages/matplotlib/legend.py#line=600), in Legend.__init__(self, parent, handles, labels, loc, numpoints, markerscale, markerfirst, reverse, scatterpoints, scatteryoffsets, prop, fontsize, labelcolor, borderpad, labelspacing, handlelength, handleheight, handletextpad, borderaxespad, columnspacing, ncols, mode, fancybox, shadow, title, title_fontsize, framealpha, edgecolor, facecolor, bbox_to_anchor, bbox_transform, frameon, handler_map, title_fontproperties, alignment, ncol, draggable)
    597 color = getattr(handle, getter_name)()
    598 if isinstance(color, np.ndarray):
    599     if (
    600             color.shape[0] == 1
--> 601             or np.isclose(color, color[0]).all()
    602     ):
    603         text.set_color(color[0])
    604     else:

IndexError: index 0 is out of bounds for axis 0 with size 0

Expected outcome

The example plot should look like this:

Image

(I managed to create this figure by changing labelcolor='linecolor' to labelcolor='C0' in the provided example.)

In words:

  1. The legend label for the histtype='step' histogram (top right) should be the same as the one for the histtype='bar' histogram (top left).
  2. The scatter plot with empty markers (bottom right) should provide the same legend as the one with filled markers (bottom left), except that the legend handles should be obviously empty for the first and filled for the latter.
  3. There should be no error.

Additional information

Might be related to #3670, #28153.

Operating system

Manjaro Linux

Matplotlib Version

3.10.3

Matplotlib Backend

module://matplotlib_inline.backend_inline

Python version

3.12.1

Jupyter version

4.4.2

Installation

pip

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      pFad - Phonifier reborn

      Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

      Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


      Alternative Proxies:

      Alternative Proxy

      pFad Proxy

      pFad v3 Proxy

      pFad v4 Proxy