Skip to content

Fix legend labelcolor=‘linecolor’ to handle all cases, including step plots and transparent markers #30299

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 7 commits into
base: main
Choose a base branch
from

Conversation

nrnavaneet
Copy link
Contributor

@nrnavaneet nrnavaneet commented Jul 12, 2025

This fix improves how labelcolor='linecolor' works in legends when artists (like step histograms or outline scatter plots) don’t have a visible face colour.

What was wrong:

  • For plots like histtype='step' or scatter with facecolors='none', the code was picking up transparent colours.
  • This caused legend text to show up in white or become invisible.

What I changed:

  • Added checks to skip empty or fully transparent colours before setting the label text colour.
  • Ensured the legend text uses the edge or line colour when face colour is not useful.
  • Updated the logic to avoid index errors and handle all common artist types.
  • A new visual test that covers four different plot types to verify labelcolor='linecolor' behaves correctly across edge-only and filled artists.

Now, legend labels always appear with the correct visible colour — matching the lines or edges in the plots.

Closes [#30298]

@rcomer
Copy link
Member

rcomer commented Jul 12, 2025

Thanks for the PR. I tried your branch with the example code from the issue and got this:

image

We still have no label showing for the top right panel and the one for the bottom right panel is now black. I think they should both be blue.

@nrnavaneet
Copy link
Contributor Author

Thanks for testing this out and for the helpful feedback, @rcomer!

I’ll take a closer look at the color resolution logic, especially around how get_facecolor and get_edgecolor interact in these scenarios. As you noted, switching to or including get_edgecolor might resolve this more cleanly.

I’ll push a follow-up commit shortly to address this, thanks again for the detailed insights!

@nrnavaneet
Copy link
Contributor Author

nrnavaneet commented Jul 12, 2025

Thanks again for the helpful feedback, @rcomer !

I’ve made the changes now. Specifically, I updated the logic to check for transparent or missing facecolors (like in outline scatter plots or step histograms) and fall back to using the edgecolor instead as you suggested. This should fix the issue with missing or incorrect legend label colors in those cases.

You can use the following script to visually confirm that the labels now pick up the expected colors across all four plot types:

Let me know if this works better now!

import matplotlib.pyplot as plt
import numpy as np

fig, axes = plt.subplots(2, 2, figsize=(8, 8))
x = np.random.randn(1000)
y = np.random.randn(1000)

# Top Left: Filled Histogram
axes[0, 0].hist(x, histtype='bar', label="filled hist", color='C0')
axes[0, 0].legend(labelcolor='linecolor')
axes[0, 0].set_title("Filled Histogram")

# Top Right: Step Histogram (edge only)
axes[0, 1].hist(x, histtype='step', label="step hist")
axes[0, 1].legend(labelcolor='linecolor')
axes[0, 1].set_title("Step Histogram")

# Bottom Left: Filled Scatter Plot
axes[1, 0].scatter(x, y, label="filled scatter", color='C2')
axes[1, 0].legend(labelcolor='linecolor')
axes[1, 0].set_title("Filled Scatter Plot")

# Bottom Right: Outline Scatter Plot
axes[1, 1].scatter(x, y, label="outline scatter", facecolors='none', edgecolors='C3')
axes[1, 1].legend(labelcolor='linecolor')
axes[1, 1].set_title("Outline Scatter Plot")

fig.suptitle("Legend Labelcolor='linecolor' – Visual Test")
plt.tight_layout()
plt.show()

@nrnavaneet nrnavaneet changed the title Fix legend labelcolor=‘linecolor’ when facecolor is ‘None’ Fix legend labelcolor=‘linecolor’ to handle all cases, including step plots and transparent markers Jul 12, 2025
Copy link

@lukashergt lukashergt left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Wow, that was fast. As mentioned in #30298, I'm not sure if generally ignoring alpha=0 is really what we want. See the currently different handling of plot and scatter:

import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 1, 10)
plt.plot(x, 'o', c='None', label="spam")
plt.scatter(x, x, c='None', label="ham")
plt.legend(loc=1, labelcolor='linecolor')
image

Currently in this PR, when c, fc and ec are all 'None', then scatter will default to black text, whereas plot will give transparent text.

I think if all color kwargs are 'None' then we indeed want that transparent text, right? Only when one of fc/ec is 'None', but the other is not, then we want 'linecolor' to pick the correct color.

@lukashergt
Copy link

This might go beyond this PR, but a few more failing examples:

import numpy as np
import matplotlib.pyplot as plt
plt.rcParams['legend.loc'] = 1
plt.rcParams['legend.framealpha'] = 1

x = np.linspace(0, 1, 10)

plt.plot(x, -x-0, 'o', c='None',            label="invisible")
plt.plot(x, -x-1, 'o',   c='b', mfc='None', label="matching handle and label color")
plt.plot(x, -x-2, 'o', mec='r', mfc='None', label="NOT MATCHING HANDLE AND LABEL COLOR!!!")
plt.plot(x, -x-3, 'o',   c='g', mec='None', label="again matching")
plt.plot(x, -x-4, 'o', mfc='m', mec='None', label="AGAIN NOT MATCHING!!!")

plt.scatter(x, -x-5,  c='None',             label="OH NO, i AM VISIBLE!!!")
plt.scatter(x, -x-6,    ec='y',  fc='None', label="yay, I work now")
plt.scatter(x, -x-7,    fc='c',  ec='None', label="yay, I still work")

plt.legend(labelcolor='linecolor')
image

Note the two failing cases 'r' and 'm'. However, note also the perfectly working alternatives 'b' and 'g'.

@nrnavaneet
Copy link
Contributor Author

nrnavaneet commented Jul 13, 2025

Thanks, man, nice examples you’ve got there 😂, they really helped clarify the edge cases! I’m actively working on addressing these inconsistencies (especially the mismatched mfc/mec ones like ‘r’ and ‘m’), and I’ll get back to you once I have a solid fix in place. Appreciate the detailed test cases! 🙌

@nrnavaneet
Copy link
Contributor Author

nrnavaneet commented Jul 13, 2025

Hey! I’ve made the changes as discussed, and all the related tests are now passing

  1. I had to update the colour_getters logic and modify a few tests where the check was comparing the full color array. Since the updated logic uses the first valid color in some cases (like gradients or arrays), I updated those tests accordingly.
  2. I’ve also added the ValueError handling to catch invalid labelcolor inputs like 'not-a-color'.
  3. On top of that, I created several new test functions at the end to cover a wide range of edge cases, including transparent colors, None, mixed facecolors, missing labels, empty color arrays, etc.

I’ve tried to ensure everything is correct, but I might’ve missed something. Feel free to point it out if so!

@nrnavaneet
Copy link
Contributor Author

I accidentally added the test file and removed it. This created the cleanliness error. Im unable to resolve the issue. Any tips or advices would be helpful

Copy link

@lukashergt lukashergt left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey! I’ve made the changes as discussed, and all the related tests are now passing

Thanks for your work! Some comments inline. From a reviewers perspective it would be nice to limit any pure reformatting to a minimum to not distract from the meaningful changes.

I accidentally added the test file and removed it. This created the cleanliness error. Im unable to resolve the issue. Any tips or advices would be helpful

I'm afraid I'm not familiar with this, so can't be of any help there. Maybe @rcomer knows how to handle this?

  1. I had to update the colour_getters logic and modify a few tests where the check was comparing the full color array. Since the updated logic uses the first valid color in some cases (like gradients or arrays), I updated those tests accordingly.

I'm not sure the changing behaviour for multi-colour objects is what we want. I think for those cases they chose the default (black) text colour deliberately. Hence the tests. (see also comments inline)

  1. On top of that, I created several new test functions at the end to cover a wide range of edge cases, including transparent colors, None, mixed facecolors, missing labels, empty color arrays, etc.

Your previous tests (e.g. from 14e0fe0) were much more specific and thus helpful, I think. In these latest tests there is not a single assertion, so these only check whether things pass syntactically, but not whether the legend label colours actually correspond to what we expect them to.

Apart from the above and inline points, I can confirm that my previous examples (#30298, #30299 (comment)) now all work correctly :)

Comment on lines -579 to +583
'linecolor': ['get_color', 'get_facecolor'],
# Set the color of legend label texts based on the specified labelcolor strategy

color_getters = { # Order of fallback functions for retrieving color
'linecolor': [
'get_markeredgecolor',
'get_edgecolor',
'get_markerfacecolor',
'get_facecolor',

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Considering that ec was not even listed under 'linecolor' previously, it might be more backwards compatible to change the ordering here, and start with fc first, then ec? It also tends to be the visually more dominant colour, e.g. for a 'stepfilled' histogram with different fc and ec, the fc will stick out more.

Comment on lines 585 to +588
'markerfacecolor': ['get_markerfacecolor', 'get_facecolor'],
'mfc': ['get_markerfacecolor', 'get_facecolor'],
'mfc': ['get_markerfacecolor', 'get_facecolor'],
'markeredgecolor': ['get_markeredgecolor', 'get_edgecolor'],
'mec': ['get_markeredgecolor', 'get_edgecolor'],
'mec': ['get_markeredgecolor', 'get_edgecolor'],

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Clean up misalignment.

Comment on lines -585 to +595
labelcolor = mpl._val_or_rc(mpl._val_or_rc(labelcolor, 'legend.labelcolor'),
'text.color')

# Resolve labelcolor from kwargs or rcParams, then fallback to text.color
labelcolor = mpl._val_or_rc(
mpl._val_or_rc(labelcolor, 'legend.labelcolor'),
'text.color'
)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nothing changed here, right? I'd keep re-formatting to a minimum. Makes reviewing easier and git diffs much more helpful.

Comment on lines -600 to +619
color.shape[0] == 1
or np.isclose(color, color[0]).all()
if color.size == 0:
continue
if color.ndim == 2:
# pick first color if multiple
color = color[0]

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this really what we want? Or would the default colour (i.e. typically black) as a neutral colour be more appropriate to represent something that has multiple colours (e.g. a scatter plot with different colour per blob)?

Comment on lines +651 to +659
# labelcolor is either 'none', a list, or a single color string
if cbook._str_equal(labelcolor, 'none'):
for text in self.texts:
text.set_color('none')

elif np.iterable(labelcolor):
for text, color in zip(self.texts,
itertools.cycle(colors.to_rgba_array(labelcolor))):
text.set_color(color)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This also hasn't actually really changed, right? I'd leave this to the original formatting.

Comment on lines -858 to +860
assert mpl.colors.same_color(text.get_color(), color)
assert mpl.colors.same_color(text.get_color(), 'black')

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why this change? This seems wrong to me...

Comment on lines -916 to +919
for text, color in zip(leg.get_texts(), ['k']):
assert mpl.colors.same_color(text.get_color(), color)
for text in leg.get_texts():
assert mpl.colors.same_color(text.get_color(), colors[0]) # 'r'

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is an example for multicoloured dots that I mentioned above, where the previous defaulting to the neutral black is probably more appropriate. The fact that this was coded up in a test shows that this was a conscious decision by someone in the past.

Comment on lines -971 to +974
for text, color in zip(leg.get_texts(), ['k']):
assert mpl.colors.same_color(text.get_color(), color)
for text in leg.get_texts():
assert mpl.colors.same_color(text.get_color(), colors[0])

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

idem

Comment on lines -989 to +991
assert mpl.colors.same_color(text.get_color(), color)
assert mpl.colors.same_color(text.get_color(), colors[0])

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

idem

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants
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