7

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.

Keith
  • 4,646
  • 7
  • 43
  • 72

2 Answers2

3

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() 
Community
  • 1
  • 1
Ed Smith
  • 12,716
  • 2
  • 43
  • 55
  • 2
    Exactly what repspects the color cycle and what does not is a bit inconsistent. There is a PR on the way to make this sort of this easier https://github.com/matplotlib/matplotlib/pull/4258 from the user side. – tacaswell May 29 '15 at 18:16
2

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

clist = rcParams['axes.prop_cycle']