|
| 1 | +""" |
| 2 | +Stacked area plot for 1D arrays inspired by Douglas Y'barbo's stackoverflow |
| 3 | +answer: |
| 4 | +http://stackoverflow.com/questions/2225995/how-can-i-create-stacked-line-graph-with-matplotlib |
| 5 | +
|
| 6 | +(http://stackoverflow.com/users/66549/doug) |
| 7 | +
|
| 8 | +""" |
| 9 | +import numpy as np |
| 10 | +import matplotlib |
| 11 | + |
| 12 | +__all__ = ['stackplot'] |
| 13 | + |
| 14 | + |
| 15 | +def stackplot(axes, x, *args, **kwargs): |
| 16 | + """Draws a stacked area plot. |
| 17 | +
|
| 18 | + Parameters |
| 19 | + ---------- |
| 20 | + *x* : 1d array of dimension N |
| 21 | + *y* : 2d array of dimension MxN, OR any number 1d arrays each of dimension |
| 22 | + 1xN. The data is assumed to be unstacked. Each of the following |
| 23 | + calls is legal: |
| 24 | +
|
| 25 | + stackplot(x, y) # where y is MxN |
| 26 | + staclplot(x, y1, y2, y3, y4) # where y1, y2, y3, y4, are all 1xNm |
| 27 | +
|
| 28 | + Keyword arguments: |
| 29 | + *colors* : A list or tuple of colors. These will be cycled through and |
| 30 | + used to colour the stacked areas. |
| 31 | + All other keyword arguments are passed to |
| 32 | + :func:`~matplotlib.Axes.fill_between` |
| 33 | +
|
| 34 | + Returns |
| 35 | + ------- |
| 36 | + *r* : A list of :class:`~matplotlib.collections.PolyCollection`, one for |
| 37 | + each element in the stacked area plot. |
| 38 | + """ |
| 39 | + |
| 40 | + if len(args) == 1: |
| 41 | + y = np.atleast_2d(*args) |
| 42 | + elif len(args) > 1: |
| 43 | + y = np.row_stack(args) |
| 44 | + |
| 45 | + colors = kwargs.pop('colors', None) |
| 46 | + if colors is not None: |
| 47 | + axes.set_color_cycle(colors) |
| 48 | + |
| 49 | + # Assume data passed has not been 'stacked', so stack it here. |
| 50 | + y_stack = np.cumsum(y, axis=0) |
| 51 | + |
| 52 | + r = [] |
| 53 | + |
| 54 | + # Color between x = 0 and the first array. |
| 55 | + r.append(axes.fill_between(x, 0, y_stack[0,:], facecolor=axes._get_lines.color_cycle.next(), **kwargs)) |
| 56 | + |
| 57 | + # Color between array i-1 and array i |
| 58 | + for i in xrange(len(y)-1): |
| 59 | + r.append(axes.fill_between(x, y_stack[i,:], y_stack[i+1,:], facecolor=axes._get_lines.color_cycle.next(), **kwargs)) |
| 60 | + return r |
0 commit comments