Skip to content

Instantly share code, notes, and snippets.

@thriveth
Last active January 2, 2016 19:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thriveth/8352565 to your computer and use it in GitHub Desktop.
Save thriveth/8352565 to your computer and use it in GitHub Desktop.
def fill_between_steps(x, y1, y2=0, h_align='mid', ax=None, **kwargs):
''' Fills a hole in matplotlib: fill_between for step plots.
Parameters :
------------
x : array-like
Array/vector of index values. These are assumed to be equally-spaced.
If not, the result will probably look weird...
y1 : array-like
Array/vector of values to be filled under.
y2 : array-Like
Array/vector or bottom values for filled area. Default is 0.
**kwargs will be passed to the matplotlib fill_between() function.
'''
# If no Axes opject given, grab the current one:
if ax is None:
ax = plt.gca()
# First, duplicate the x values
xx = x.repeat(2)[1:]
# Now: the average x binwidth
xstep = sp.repeat((x[1:] - x[:-1]), 2)
xstep = sp.concatenate(([xstep[0]], xstep, [xstep[-1]]))
# Now: add one step at end of row.
xx = sp.append(xx, xx.max() + xstep[-1])
# Make it possible to chenge step alignment.
if h_align == 'mid':
xx -= xstep / 2.
elif h_align == 'right':
xx -= xstep
# Also, duplicate each y coordinate in both arrays
y1 = y1.repeat(2)#[:-1]
if type(y2) == sp.ndarray:
y2 = y2.repeat(2)#[:-1]
# now to the plotting part:
ax.fill_between(xx, y1, y2=y2, **kwargs)
return ax
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment