Is there a way to change the color name's color in mplstyle file?

Viewed 166

I would like to assign colors of a matplotlib plot e.g. by writing plt.plot(x,y, color="red"). But "red" should be a color I predefined in a mplstyle file.

I know I can change the default colors in the mplstyle file that are used for drawing by

 # colors: blue, red, green
axes.prop_cycle: cycler('color', [(0,0.3,0.5),(0.9, 0.3,0.3),(0.7, 0.8, 0.3)])

But appart from that I sometimes need to draw something with specific colors

plt.bar([0,1],[1,1],color=["green","red"])

Unfortunately, those colors always refer to the predefined "green" and "red" in matplotlib. I would know like to assign a my green for "green" and my red for "red".

Of course, I could do a workaround and define a variable as, say a RGB-tuple

red = (0.9, 0.3,0.3)
green = (0.7, 0.8, 0.3)
plt.bar([0,1],[10,8],color=[red,green])

but I think more natural would be to redefine the colors referred to by "green" and "red".

Does any of you know how I can change a color name's color in the mplstyle file?

2 Answers

The list of color names is stored in matplotlib.colors.get_named_colors_mapping() and you can edit it.

import matplotlib.colors
import matplotlib.pyplot as plt

color_map = matplotlib.colors.get_named_colors_mapping()
color_map["red"] = "#ffaaaa"
color_map["green"] = "#aaffaa"

plt.bar([0, 1], [1, 1], color=["green", "red"])
plt.show()

Can you give a little more context or code? Or on how you're trying to accomplish this?

Without knowing, here is one suggestion from the documentation:

mpl.rcParams['axes.prop_cycle'] = cycler(color=['r', 'g', 'b', 'y'])
plt.plot(data)  # first color is red

The above can also be put into your matplotlibrc file.

Related