Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions examples/pylab_examples/stackplot_demo.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import numpy as np
from matplotlib import pyplot as plt

fnx = lambda : np.random.randint(5, 50, 10)
y = np.row_stack((fnx(), fnx(), fnx()))
x = np.arange(10)

fig = plt.figure()
ax = fig.add_subplot(111)
ax.stackplot(x, y)
plt.show()
5 changes: 5 additions & 0 deletions lib/matplotlib/axes.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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()
Expand Down
42 changes: 42 additions & 0 deletions lib/matplotlib/stackplot.py
Original file line number Diff line number Diff line change
@@ -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