You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
ax.set_prop_cycle does not allow 'CN' colors #14221
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.
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'.
@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?
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'].
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 ?
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?
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?
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.
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 .
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.
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).
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:
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
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!
Activity
timhoffm commentedon May 14, 2019
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'.
u55 commentedon May 14, 2019
@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?
timhoffm commentedon May 14, 2019
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'].tacaswell commentedon May 14, 2019
There is some confusing naming here as
rcparams_setuphas acyclerfunction which wrapscycler.cyclerand we import various places.In
Axes.set_prop_cyclewe 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
which does the look up against the default color cycle before you pass it in.
u55 commentedon May 15, 2019
@tacaswell Indeed, my use-case is simply that it is easier for me to remember, and faster to type:
than:
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 forAxes.set_prop_cycleis over-zealous. If so, then why not fix it?Also, I don't understand the validation for parsing rcParams. The
axes.prop_cycleentry 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?anntzer commentedon May 15, 2019
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?
timhoffm commentedon May 15, 2019
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.
[-]Cycler does not allow 'CN' colors[/-][+]`ax.set_prop_cycle` does not allow 'CN' colors[/+]tacaswell commentedon May 15, 2019
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
CNagainst the default cycle from rcparams because the Axes does not actually hold the underlyingcyclerinstance, it only holds anitertools.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 .timhoffm commentedon May 16, 2019
What about making a
Colorclass? We could internally use this and return it forget_color(). That would allowColor('r') == 'red'so thatget_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_facecolorcurrently normalizes to RGBA, butText.set_colorjust keeps it as is.and
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.anntzer commentedon May 16, 2019
We could make Color inherit from tuple, but just override
__eq__so that it converts the other argument withto_color_rgbafirst 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
angelazb commentedon Mar 17, 2020
Anyone currently working on this? We would like to give it a shot.
5 remaining items
hmedina commentedon Sep 27, 2022
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()andmatplotlib.patches.Rectangle()support supplying aCNalias, stackplot throws a ValueError. For example:Color assignment for largest-complex
github-actions commentedon Sep 3, 2025
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!
hmedina commentedon Sep 3, 2025
Just a comment to deal with the auto-labeler for inactivity.
The issue at the top of this thread persists:
However, the situation I mentioned in my post has been resolved and does not produce errors and yields the expected plot:
Fix stackplot to not modify Axes cycler with colors