Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

matplotlib fill_between does not cycle through colours

Most plotting methods like plot() and errorbar automatically change to the next colour in the color_palette when you plot multiple things on the same graph. For some reason this is not the case for fill_between(). I know that I could hard-code this but it is done in a loop which makes it annoying. Is there a good way to get around this?

import numpy as np
import matplotlib.pyplot as plt

x = np.asarray([1.0, 2.0, 3.0, 4.0, 5.0])
y = np.asarray([1.0, 2.0, 3.0, 4.0, 5.0])
xerr = np.asarray([0.2, 0.4, 0.6, 0.8, 1.0])
yerr = np.asarray([0.1, 0.2, 0.3, 0.4, 0.5])

plt.fill_between(x, y-yerr, y+yerr,alpha=0.5)
plt.fill_between(y,x-xerr,x+xerr,alpha=0.5)

plt.show() 

Maybe just to get the current position in the palette and iterate to the next will be enough.

like image 733
Keith Avatar asked May 29 '15 17:05

Keith


2 Answers

Strange, it seems that even calling ax._get_patches_for_fill.set_color_cycle(clist) or ax.set_color_cycle(np.roll(clist, -1)) explicitly doesn't reinstate the color cycle (see this answer). This may be because fill between doesn't create a conventional patch or line object (or it may be a bug?). Anyway, you could manually call a cycle on the colors like in the axis function ax.set_color_cycle,

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rcParams
import itertools

clist = rcParams['axes.color_cycle']
cgen = itertools.cycle(clist)

x = np.asarray([1.0, 2.0, 3.0, 4.0, 5.0])
y = np.asarray([1.0, 2.0, 3.0, 4.0, 5.0])
xerr = np.asarray([0.2, 0.4, 0.6, 0.8, 1.0])
yerr = np.asarray([0.1, 0.2, 0.3, 0.4, 0.5])

fig, ax = plt.subplots(1,1)
ax.fill_between(x, y-yerr, y+yerr,alpha=0.5, facecolor=cgen.next())
ax.fill_between(y,x-xerr,x+xerr,alpha=0.5, facecolor=cgen.next())

plt.show() 
like image 116
Ed Smith Avatar answered Oct 07 '22 22:10

Ed Smith


In matplotlib 3.3.3 following adjustment in the syntax proposed by Ed Smith is necessary:

clist = rcParams['axes.prop_cycle']
like image 24
Elia Daniele Avatar answered Oct 07 '22 20:10

Elia Daniele