Skip to content

ax.set_prop_cycle does not allow 'CN' colors #14221

Open

Description

@u55

Hi matplotlib developers,
I was surprised to discover that the cycler validation does not allow colors specified with 'CN' syntax.

import numpy as np
import matplotlib.pyplot as plt
from cycler import cycler

fig, ax = plt.subplots()
ax.set_prop_cycle(cycler(color=['C1', 'C0'])) # raises ValueError
# ax.set_prop_cycle(cycler(color=['tab:orange', 'tab:blue'])) # works fine
ax.plot(np.arange(9))
ax.plot(-np.arange(9))
plt.show()

If matplotlib can differentiate between {'C0', 'C1', 'C2', 'C3', 'C4', 'C5', 'C6', 'C7', 'C8', 'C9'} colors and {'b', 'g', 'r', 'c', 'm', 'y', 'k', 'w'} colors (case insensitive) anywhere else that a color is specified, then it seems to me that the cycler should be able to handle this as well. Thanks.

Tested with matplotlib 3.0.3 and python 3.7.3 (Anaconda) on Windows 10.

Activity

  1. timhoffm commented on May 14, 2019

    @timhoffm
    Member

    That cannot be done reliably. 'CN' indexes into the default property cycle at execution time, which then just might be the cycler you created. Therefore cyclers themselves do not accept 'CN'.

  2. u55 commented on May 14, 2019

    @u55
    ContributorAuthor

    @timhoffm Thanks for the comment, but I don't fully understand. Are you saying it is a recursion issue? Why can't the cycler evaluate its input arguments at instantiation using the "currently defined" cycler, then use those values to create the "new" cycler?

  3. timhoffm commented on May 14, 2019

    @timhoffm
    Member

    Cyclers don't do anything at instantiation time. Actually, it's not even the cycler that resolves the color. The color is resolved in the respective plotting function when it's called. If you want to use the colors of the existing cycler to create a new one, you'll have to get it's colors explicitly via cycler.by_key()['color'].

  4. tacaswell commented on May 14, 2019

    @tacaswell
    Member

    There is some confusing naming here as rcparams_setup has a cycler function which wraps cycler.cycler and we import various places.

    In Axes.set_prop_cycle we are re-using the validation code that we use when parsing rcparams from file (which as part of start up, is clearly not going to work as we are loading the cycle to be the default cycle).
    It would certainly be possible to special case the color key in Axes.set_prop_cycle, before we validate, but I am not sure it is worth it. @u55 What is the use-case for this ?

    You can currently get this to work via

    import matplotlib.colors as mcolors
    ax.set_prop_cycle(cycler(color=mcolors.to_rgba_array(['C1', 'C0'])))

    which does the look up against the default color cycle before you pass it in.

  5. u55 commented on May 15, 2019

    @u55
    ContributorAuthor

    @tacaswell Indeed, my use-case is simply that it is easier for me to remember, and faster to type:

    ax.set_prop_cycle(cycler(color=['C1', 'C0']))

    than:

    import matplotlib.colors as mcolors
    ax.set_prop_cycle(cycler(color=mcolors.to_rgba_array(['C1', 'C0'])))

    which seems like a hackish work-around.

    Furthermore, as an end user, it seems inconsistent and unexpected that every other color specification (i.e. 'tab:blue', 'xkcd:sky blue', 'b', '#0000FF', 'blue', (0, 0, 1), '0.5', etc.) works fine with the prop_cycle but 'C0', etc., fails. It sounds like you are saying that the validation for Axes.set_prop_cycle is over-zealous. If so, then why not fix it?

    Also, I don't understand the validation for parsing rcParams. The axes.prop_cycle entry in my '.matplotlibrc' file is commented out, which means the actual default values must be hard-coded somewhere. Why can't 'CN' index into this default color cycle?

  6. anntzer commented on May 15, 2019

    @anntzer
    Contributor

    Given the discussion at #12967 I think eagerly resolving colors (against whatever the previous color cycle (the default one if there's none yet, e.g. in the matplotlibrc) is) makes sense here?

  7. timhoffm commented on May 15, 2019

    @timhoffm
    Member

    Probably yes. But I really recommend not to add this additional functionality until we've determined and implemented a clear global resolution strategy - when and from which cycler. Otherwise this implementation might not match the desired behavior.

  8. added this to the v3.2.0 milestone on May 15, 2019
  9. changed the title [-]Cycler does not allow 'CN' colors[/-] [+]`ax.set_prop_cycle` does not allow 'CN' colors[/+] on May 15, 2019
  10. tacaswell commented on May 15, 2019

    @tacaswell
    Member

    Updated the issue title to be a bit clearer about where the validation is being done.

    @timhoffm @anntzer Seems reasonable to move to eager color evaluation. This also would also move us a long way towards "always store colors and RBGA float tuples internally". On the other hand, this would mean that a.set_color(C); C != a.get_color() in general which is not great. Not sure carrying 2 copies of the color (one 'human readable', one 'RGBA') is a better path though.

    Currently, we have to resolve CN against the default cycle from rcparams because the Axes does not actually hold the underlying cycler instance, it only holds an itertools.cycle() of the cycler. Even though it cuts off some use-cases (like having 4 axes each with their own property cycler that have different colors and then expecting 'C0' to have different values in each), it greatly simplifies both implementation and how hard it is to explain to always go against the default cycle .

  11. timhoffm commented on May 16, 2019

    @timhoffm
    Member

    What about making a Color class? We could internally use this and return it for get_color(). That would allow Color('r') == 'red' so that get_color() == 'r', get_color() == 'red', get_color() == (1, 0, 0) all would work.

    Of course, this is a breaking API change, however AFAIC we're not consistent here anyway. E.g. Rectangle.set_facecolor currently normalizes to RGBA, but Text.set_color just keeps it as is.

    In [12]: from matplotlib.patches import Rectangle                                                                     
    In [13]: r = Rectangle((0, 0), 1,1)                                                                                   
    
    In [16]: r.get_facecolor()                                                                                            
    Out[16]: (0.12156862745098039, 0.4666666666666667, 0.7058823529411765, 1.0)
    
    In [17]: r.set_color('b')                                                                                             
    
    In [18]: r.get_facecolor()                                                                                            
    Out[18]: (0.0, 0.0, 1.0, 1)
    

    and

    In [19]: from matplotlib.text import Text                                                                             
    
    In [20]: Text(0, 0, 'test')                                                                                            
    Out[20]: Text(0, 0, 'test')
    
    In [23]: t.get_color()                                                                                                
    Out[23]: 'black'
    
    In [24]: t.set_color('r')                                                                                             
    
    In [25]: t.get_color()                                                                                                
    Out[25]: 'r'
    

    We would have to see though, how to handle multiple colors - the equivalence of Nx3 or Nx4 RGB(A) arrays if we have really many colors. Probably needs some sort of dedicated class ColorList / ColorSequence / ColorArray.

  12. anntzer commented on May 16, 2019

    @anntzer
    Contributor

    We could make Color inherit from tuple, but just override __eq__ so that it converts the other argument with to_color_rgba first before comparing (possibly, also stash the arguments with which it was constructed and use it in its __str__/__repr__ as well).

    So something very approximately like

    class Color(tuple):
        def __new__(cls, *args, **kwargs):
            self = cls(*mcolors.to_rgba(*args, **kwargs))
            self._args, self._kwargs = args, kwargs
            return self
        def __eq__(self, other):
            return tuple(self) == mcolors.to_rgba(other)
        def __str__(self):
            return super().__str__(self) + f" (a.k.a. Color(*{self._args}, **{self._kwargs}))"
  13. modified the milestones: v3.2.0, v3.3.0 on Aug 15, 2019
  14. angelazb commented on Mar 17, 2020

    @angelazb

    Anyone currently working on this? We would like to give it a shot.

  15. 5 remaining items

  16. modified the milestones: v3.5.0, v3.6.0 on Sep 25, 2021
  17. modified the milestones: v3.6.0, v3.7.0 on Jul 8, 2022
  18. hmedina commented on Sep 27, 2022

    @hmedina

    I arrived at this issue via a problem with stackplot.

    Usecase: I am producing various types of plots (some use rectangle collections, some regular plot-lines, some stacked plots) and wish to keep the colors synchronized across plot types for consistency and ease of comparison.

    While ax.plot() and matplotlib.patches.Rectangle() support supplying a CN alias, stackplot throws a ValueError. For example:

    import matplotlib.pyplot as plt
    from matplotlib.patches import Rectangle
    import numpy
    
    my_data = numpy.array([[1, 1, 1], [1, 2, 3], [4, 3, 2]])
    fig, ax = plt.subplots()
    ax.plot([1, 3], [1, 3], color='C0')
    ax.add_patch(Rectangle(xy=(1.5, 1.5), width=0.5, height=0.5, facecolor='C1'))
    ax.stackplot([1, 2, 3], my_data, colors=['C2', 'C3', 'C4'])
    plt.show()
    
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "/home/hmedina/.local/lib/python3.9/site-packages/matplotlib/__init__.py", line 1412, in inner
        return func(ax, *map(sanitize_sequence, args), **kwargs)
      File "/home/hmedina/.local/lib/python3.9/site-packages/matplotlib/stackplot.py", line 73, in stackplot
        axes.set_prop_cycle(color=colors)
      File "/home/hmedina/.local/lib/python3.9/site-packages/matplotlib/axes/_base.py", line 1575, in set_prop_cycle
        prop_cycle = cycler(*args, **kwargs)
      File "/home/hmedina/.local/lib/python3.9/site-packages/matplotlib/rcsetup.py", line 695, in cycler
        vals = validator(vals)
      File "/home/hmedina/.local/lib/python3.9/site-packages/matplotlib/rcsetup.py", line 107, in f
        val = [scalar_validator(v) for v in s
      File "/home/hmedina/.local/lib/python3.9/site-packages/matplotlib/rcsetup.py", line 107, in <listcomp>
        val = [scalar_validator(v) for v in s
      File "/home/hmedina/.local/lib/python3.9/site-packages/matplotlib/rcsetup.py", line 285, in validate_color_for_prop_cycle
        raise ValueError(f"Cannot put cycle reference ({s!r}) in prop_cycler")
    ValueError: Cannot put cycle reference ('C2') in prop_cycler
    
  19. added a commit that references this issue on Sep 27, 2022
  20. github-actions commented on Sep 3, 2025

    @github-actions

    This issue has been marked "inactive" because it has been 365 days since the last comment. If this issue is still present in recent Matplotlib releases, or the feature request is still wanted, please leave a comment and this label will be removed. If there are no updates in another 30 days, this issue will be automatically closed, but you are free to re-open or create a new issue if needed. We value issue reports, and this procedure is meant to help us resurface and prioritize issues that have not been addressed yet, not make them disappear. Thanks for your help!

  21. hmedina commented on Sep 3, 2025

    @hmedina

    Just a comment to deal with the auto-labeler for inactivity.

    • Python 3.13.2
    • MatPlotLib 3.10.6

    The issue at the top of this thread persists:

    >>> import numpy as np
    ... import matplotlib.pyplot as plt
    ... from cycler import cycler
    ...
    ... fig, ax = plt.subplots()
    ... ax.set_prop_cycle(cycler(color=['C1', 'C0']))
    ...
    Traceback (most recent call last):
      File "<python-input-4>", line 6, in <module>
        ax.set_prop_cycle(cycler(color=['C1', 'C0']))
        ~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/home/hmedina/matplotlib_test/lib/python3.13/site-packages/matplotlib/axes/_base.py", line 1663, in set_prop_cycle
        prop_cycle = cycler(*args, **kwargs)
      File "/home/hmedina/matplotlib_test/lib/python3.13/site-packages/matplotlib/rcsetup.py", line 740, in cycler
        return validate_cycler(args[0])
      File "/home/hmedina/matplotlib_test/lib/python3.13/site-packages/matplotlib/rcsetup.py", line 868, in validate_cycler
        _prop_validators[key](vals)
        ~~~~~~~~~~~~~~~~~~~~~^^^^^^
      File "/home/hmedina/matplotlib_test/lib/python3.13/site-packages/matplotlib/rcsetup.py", line 118, in f
        val = [scalar_validator(v) for v in s
               ~~~~~~~~~~~~~~~~^^^
      File "/home/hmedina/matplotlib_test/lib/python3.13/site-packages/matplotlib/rcsetup.py", line 307, in validate_color_for_prop_cycle
        raise ValueError(f"Cannot put cycle reference ({s!r}) in prop_cycler")
    ValueError: Cannot put cycle reference ('C1') in prop_cycler

    However, the situation I mentioned in my post has been resolved and does not produce errors and yields the expected plot:

    >>> import matplotlib.pyplot as plt
    ... from matplotlib.patches import Rectangle
    ... import numpy
    ...
    ... my_data = numpy.array([[1, 1, 1], [1, 2, 3], [4, 3, 2]])
    ... fig, ax = plt.subplots()
    ... ax.plot([1, 3], [1, 3], color='C0')
    ...
    [<matplotlib.lines.Line2D object at 0x71e626648f50>]
    >>> ax.stackplot([1, 2, 3], my_data, colors=['C2', 'C3', 'C4'])
    [<matplotlib.collections.FillBetweenPolyCollection object at 0x71e626673230>, <matplotlib.collections.FillBetweenPolyCollection object at 0x71e67b1ef390>, <matplotlib.collections.FillBetweenPolyCollection object at 0x71e626501450>]
    >>> ax.add_patch(Rectangle(xy=(1.5, 1.5), width=0.5, height=0.5, facecolor='C1'))
    <matplotlib.patches.Rectangle object at 0x71e626501950>
    >>> plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions