How do I make bar plots automatically cycle across different colors?


In matplotlib, line plots color cycle automatically. These two line plots would have different colors.

axes.plot(x1, y)
axes.plot(x2, y)

However, bar plots don't. Both these data series will have blue bars., y), y)

How do I make bar plots cycle automatically across a predefined set of colors?

8/29/2010 5:04:57 AM

Accepted Answer

Optional: To get full control over the style of your figures use an existing mplstyle as a template:

adjust the parameter : axes.prop_cycle: cycler('color', [....])

load your style:

from matplotlib import style
style.use ('PATH TO YOUR MPL STYLE')

You can cycle through your or the default style color cycle almost any way you want:

import matplotlib.pyplot as plt

prop_iter = iter(plt.rcParams['axes.prop_cycle'])

for i in range(0,len(x)):[i],y[i],color=next(prop_iter)['color'])

plt.rcParams['axes.prop_cycle'] grabs all cycles so you need to select the correct cycler using the key ['color'].

You can drop the iterator creation and use list comprehension and zip to create one liners:

import matplotlib.pyplot as plt

prop = plt.rcParams['axes.prop_cycle']
[[0],param[1],color=param[2]['color']) for param in zip(x,y,prop)]

enter image description here

6/13/2016 12:32:06 AM

Would something along these lines do it for you?

from matplotlib import cm
import matplotlib.pyplot as plt


for i in range(0,len(x)):[i],y[i],color=cm.jet(1.*i/len(x)))

More on colormaps.

EDIT: See this example for how to cycle over a predefined set of colors.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow