Permalink
Browse files

Added new plot style to axes: stackplot.

Stackplot adds the feature request in issue #359
(matplotlib#359) and borrows
heavily from Doug Y'barbo's stackoverflow answer
(http://stackoverflow.com/questions/2225995/how-can-i-create-stacked-line-graph-with-matplotlib).
  • Loading branch information...
1 parent 50b78f7 commit 3b383eeb8846da41949d21d88874c17ad26dbbfe @dmcdougall committed Apr 7, 2012
Showing with 47 additions and 0 deletions.
  1. +5 −0 lib/matplotlib/axes.py
  2. +42 −0 lib/matplotlib/stackplot.py
View
@@ -29,6 +29,7 @@
import matplotlib.spines as mspines
import matplotlib.quiver as mquiver
import matplotlib.scale as mscale
+import matplotlib.stackplot as mstack
import matplotlib.streamplot as mstream
import matplotlib.table as mtable
import matplotlib.text as mtext
@@ -6382,6 +6383,10 @@ def quiver(self, *args, **kw):
return q
quiver.__doc__ = mquiver.Quiver.quiver_doc
+ def stackplot(self, x, y):
+ return mstack.stackplot(self, x, y)
+ stackplot.__doc__ = mstack.stackplot.__doc__
+
def streamplot(self, x, y, u, v, density=1, linewidth=None, color=None,
cmap=None, arrowsize=1, arrowstyle='-|>', minlength=0.1):
if not self._hold: self.cla()
@@ -0,0 +1,42 @@
+"""
+Stacked area plot for 1D arrays inspired by Douglas Y'barbo's stackoverflow
+answer:
+http://stackoverflow.com/questions/2225995/how-can-i-create-stacked-line-graph-with-matplotlib
+
+(http://stackoverflow.com/users/66549/doug)
+
+"""
+import numpy as np
+import matplotlib
+
+__all__ = ['stackplot']
+
+
+def stackplot(axes, x, y):
+ """Draws a stacked area plot.
+
+ Parameters
+ ----------
+ *x* : 1d array of dimension N
+ *y* : 2d array of dimension MxN
+
+ Returns
+ -------
+ *r* : A list of `matplotlib.collections.PolyCollection`, one for each
+ element in the stacked area plot.
+ """
+
+ y = np.atleast_2d(y)
+
+ # Assume data passed has not been 'stacked', so stack it here.
+ y_stack = np.cumsum(y, axis=0)
+
+ r = []
+
+ # Color between x = 0 and the first array.
+ r.append(axes.fill_between(x, 0, y_stack[0,:], facecolor=axes._get_lines.color_cycle.next()))
+
+ # Color between array i-1 and array i
+ for i in xrange(len(y)-1):
+ r.append(axes.fill_between(x, y_stack[i-1,:], y_stack[i,:], facecolor=axes._get_lines.color_cycle.next()))
+ return r

0 comments on commit 3b383ee

Please sign in to comment.