question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Creating a legend when `"legend.facecolor"` is set to `"inherit"` raises an error

See original GitHub issue

Description

I initially made a comment in #272, but this issue appears to be much more general. It seems that when using the default matplotlib style, and proplot axes that creating a legend raises an error.

Steps to reproduce

A “Minimal, Complete and Verifiable Example” will make it much easier for maintainers to help you.

import proplot
proplot.config.use_style("default")  # This line is key for the error
fig, ax = proplot.subplots(ncols=1, nrows=1)

ax.plot([0, 1], [0, 1], label="a")
ax.legend()

Expected behavior: [What you expected to happen]

No error.

Actual behavior: [What actually happened]

This error is raised:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-8-cd17e0d9dde1> in <module>
      4 
      5 ax.plot([0, 1], [0, 1], label="a")
----> 6 ax.legend()

~/proplot/proplot/axes/base.py in legend(self, handles, labels, loc, location, queue, **kwargs)
   2908             self._register_guide('legend', (handles, labels), loc, **kwargs)
   2909         else:
-> 2910             leg = self._draw_legend(handles, labels, loc=loc, **kwargs)
   2911             return leg
   2912 

~/proplot/proplot/axes/base.py in _draw_legend(self, handles, labels, loc, width, pad, space, align, frame, frameon, ncol, ncols, alphabetize, center, order, label, title, fontsize, fontweight, fontcolor, titlefontsize, titlefontweight, titlefontcolor, handle_kw, handler_map, **kwargs)
   2814             kwargs.update({key: kw_frame.pop(key) for key in ('shadow', 'fancybox')})
   2815             objs = [lax._parse_ordinary_legend(pairs, ncol=ncol, order=order, **kwargs)]
-> 2816             objs[0].legendPatch.update(kw_frame)
   2817         for obj in objs:
   2818             if hasattr(lax, 'legend_') and lax.legend_ is None:

~/miniconda3/envs/fv3net/lib/python3.7/site-packages/matplotlib/artist.py in update(self, props)
   1004 
   1005         with cbook._setattr_cm(self, eventson=False):
-> 1006             ret = [_update_property(self, k, v) for k, v in props.items()]
   1007 
   1008         if len(ret):

~/miniconda3/envs/fv3net/lib/python3.7/site-packages/matplotlib/artist.py in <listcomp>(.0)
   1004 
   1005         with cbook._setattr_cm(self, eventson=False):
-> 1006             ret = [_update_property(self, k, v) for k, v in props.items()]
   1007 
   1008         if len(ret):

~/miniconda3/envs/fv3net/lib/python3.7/site-packages/matplotlib/artist.py in _update_property(self, k, v)
   1001                     raise AttributeError('{!r} object has no property {!r}'
   1002                                          .format(type(self).__name__, k))
-> 1003                 return func(v)
   1004 
   1005         with cbook._setattr_cm(self, eventson=False):

~/miniconda3/envs/fv3net/lib/python3.7/site-packages/matplotlib/patches.py in set_facecolor(self, color)
    355         """
    356         self._original_facecolor = color
--> 357         self._set_facecolor(color)
    358 
    359     def set_color(self, c):

~/miniconda3/envs/fv3net/lib/python3.7/site-packages/matplotlib/patches.py in _set_facecolor(self, color)
    343             color = mpl.rcParams['patch.facecolor']
    344         alpha = self._alpha if self._fill else 0
--> 345         self._facecolor = colors.to_rgba(color, alpha)
    346         self.stale = True
    347 

~/miniconda3/envs/fv3net/lib/python3.7/site-packages/matplotlib/colors.py in to_rgba(c, alpha)
    183         rgba = None
    184     if rgba is None:  # Suppress exception chaining of cache lookup failure.
--> 185         rgba = _to_rgba_no_colorcycle(c, alpha)
    186         try:
    187             _colors_full_map.cache[c, alpha] = rgba

~/miniconda3/envs/fv3net/lib/python3.7/site-packages/matplotlib/colors.py in _to_rgba_no_colorcycle(c, alpha)
    259                     f"Value must be within 0-1 range")
    260             return c, c, c, alpha if alpha is not None else 1.
--> 261         raise ValueError(f"Invalid RGBA argument: {orig_c!r}")
    262     # tuple color.
    263     c = np.array(c)

ValueError: Invalid RGBA argument: 'inherit'

Equivalent steps in matplotlib

Please make sure this bug is related to a specific proplot feature. If you’re not sure, try to replicate it with the native matplotlib API. Matplotlib bugs belong on the matplotlib github page.

fig, ax = plt.subplots(1, 1)
ax.plot([0, 1], [0, 1], label="a")
ax.legend()

Proplot version

Paste the results of import matplotlib; print(matplotlib.__version__); import proplot; print(proplot.version)here.

3.2.2
0.9.5.post1

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Comments:5

github_iconTop GitHub Comments

2reactions
spencerkclarkcommented, Nov 3, 2021

Very nice, thanks!

1reaction
spencerkclarkcommented, Oct 29, 2021

A workaround for this is to explicitly set the "legend.facecolor" style parameter after setting the default matplotlib style:

import proplot
proplot.config.use_style("default")
proplot.rc["legend.facecolor"] = "white"
fig, ax = proplot.subplots(ncols=1, nrows=1)

ax.plot([0, 1], [0, 1], label="a")
ax.legend()
Read more comments on GitHub >

github_iconTop Results From Across the Web

How to change the legend edgecolor and facecolor in matplotlib
Using matplotlib.pyplot, plt.legend(facecolor='white', framealpha=1) will give your legend a white background without transparency.
Read more >
matplotlib styles - setting a legend's background color? #4360
Is there a way to change a legend's background color using styles (or ... set a value of "inherit" to legend.facecolor and legend.edgecolor....
Read more >
Change Legend background using facecolor in MatplotLib
Create data. Change the background color of a legend. ... Use the facecolor argument to plt.legend() to specify the legend background color.
Read more >
matplotlib.figure.Figure — Matplotlib 2.1.2 documentation
If shadow is activated and framealpha is None the default value is being ignored. facecolor : None or “inherit” or a color spec....
Read more >
What's new? — ProPlot documentation
Make docstring utils explicitly private and convert _snippets dictionary to ... Change default rc['legend.facecolor'] to white instead of inheriting from ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found