Revision: 5221
          http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5221&view=rev
Author:   mmetz_bn
Date:     2008-05-23 00:51:20 -0700 (Fri, 23 May 2008)

Log Message:
-----------
Major hist() revision

Modified Paths:
--------------
    trunk/matplotlib/CHANGELOG
    trunk/matplotlib/examples/pylab/histogram_demo.py
    trunk/matplotlib/lib/matplotlib/axes.py

Added Paths:
-----------
    trunk/matplotlib/examples/pylab/histogram_demo_extended.py

Removed Paths:
-------------
    trunk/matplotlib/examples/pylab/histogram_demo_cumulative.py
    trunk/matplotlib/examples/pylab/histogram_demo_step.py

Modified: trunk/matplotlib/CHANGELOG
===================================================================
--- trunk/matplotlib/CHANGELOG  2008-05-22 21:49:25 UTC (rev 5220)
+++ trunk/matplotlib/CHANGELOG  2008-05-23 07:51:20 UTC (rev 5221)
@@ -1,3 +1,8 @@
+2008-05-23 Major revision of hist(). Can handle 2D arrays and create
+           stacked histogram plots; keyword 'width' deprecated and
+           rwidth (relative width) introduced; align='edge' changed
+           to center of bin - MM
+
 2008-05-22 Added support for ReST-based doumentation using Sphinx.
            Documents are located in doc/, and are broken up into
            a users guide and an API reference. To build, run the

Modified: trunk/matplotlib/examples/pylab/histogram_demo.py
===================================================================
--- trunk/matplotlib/examples/pylab/histogram_demo.py   2008-05-22 21:49:25 UTC 
(rev 5220)
+++ trunk/matplotlib/examples/pylab/histogram_demo.py   2008-05-23 07:51:20 UTC 
(rev 5221)
@@ -1,23 +1,23 @@
 #!/usr/bin/env python
-from pylab import *
+import pylab as P
 
 mu, sigma = 100, 15
-x = mu + sigma*randn(10000)
+x = mu + sigma*P.randn(10000)
 
 # the histogram of the data
-n, bins, patches = hist(x, 50, normed=1)
-setp(patches, 'facecolor', 'g', 'alpha', 0.75)
+n, bins, patches = P.hist(x, 50, normed=1)
+P.setp(patches, 'facecolor', 'g', 'alpha', 0.75)
 
 # add a 'best fit' line
-y = normpdf( bins, mu, sigma)
-l = plot(bins, y, 'r--')
-setp(l, 'linewidth', 1)
+y = P.normpdf( bins, mu, sigma)
+l = P.plot(bins, y, 'r--')
+P.setp(l, 'linewidth', 1)
 
-xlabel('Smarts')
-ylabel('Probability')
-title(r'$\mathrm{Histogram\ of\ IQ:}\ \mu=100,\ \sigma=15$')
-axis([40, 160, 0, 0.03])
-grid(True)
+P.xlabel('Smarts')
+P.ylabel('Probability')
+P.title(r'$\mathrm{Histogram\ of\ IQ:}\ \mu=100,\ \sigma=15$')
+P.axis([40, 160, 0, 0.03])
+P.grid(True)
 
-#savefig('histogram_demo',dpi=72)
-show()
+#P.savefig('histogram_demo',dpi=72)
+P.show()

Deleted: trunk/matplotlib/examples/pylab/histogram_demo_cumulative.py
===================================================================
--- trunk/matplotlib/examples/pylab/histogram_demo_cumulative.py        
2008-05-22 21:49:25 UTC (rev 5220)
+++ trunk/matplotlib/examples/pylab/histogram_demo_cumulative.py        
2008-05-23 07:51:20 UTC (rev 5221)
@@ -1,33 +0,0 @@
-#!/usr/bin/env python
-from pylab import *
-
-mu, sigma = 100, 25
-x = mu + sigma*randn(10000)
-
-# the histogram of the data
-n, bins, patches = hist(x, 50, normed=1, histtype='step', cumulative=True)
-setp(patches, 'facecolor', 'g', 'alpha', 0.75)
-
-# add a 'best fit' line
-y = normpdf( bins, mu, sigma).cumsum()
-y /= y[-1]
-l = plot(bins, y, 'k--', linewidth=1.5)
-
-# overlay the first histogram with a second one
-# were the data has a smaller standard deviation
-mu, sigma = 100, 10
-x = mu + sigma*randn(10000)
-
-n, bins, patches = hist(x, bins=bins, normed=1, histtype='step', 
cumulative=True)
-setp(patches, 'facecolor', 'r', 'alpha', 0.25)
-
-# add a 'best fit' line
-y = normpdf( bins, mu, sigma).cumsum()
-y /= y[-1]
-l = plot(bins, y, 'k--', linewidth=1.5)
-
-grid(True)
-ylim(0, 1.1)
-
-#savefig('histogram_demo',dpi=72)
-show()
\ No newline at end of file

Added: trunk/matplotlib/examples/pylab/histogram_demo_extended.py
===================================================================
--- trunk/matplotlib/examples/pylab/histogram_demo_extended.py                  
        (rev 0)
+++ trunk/matplotlib/examples/pylab/histogram_demo_extended.py  2008-05-23 
07:51:20 UTC (rev 5221)
@@ -0,0 +1,79 @@
+#!/usr/bin/env python
+import pylab as P
+
+#
+# The hist() function now has a lot more options
+#
+
+#
+# first create a single histogram
+#
+mu, sigma = 200, 25
+x = mu + sigma*P.randn(10000)
+
+# the histogram of the data with histtype='step'
+n, bins, patches = P.hist(x, 50, normed=1, histtype='step')
+P.setp(patches, 'facecolor', 'g', 'alpha', 0.75)
+
+# add a line showing the expected distribution
+y = P.normpdf( bins, mu, sigma)
+l = P.plot(bins, y, 'k--', linewidth=1.5)
+
+
+#
+# create a histogram by providing the bin edges (unequally spaced)
+#
+P.figure()
+
+bins = [100,125,150,160,170,180,190,200,210,220,230,240,250,275,300]
+# the histogram of the data with histtype='step'
+n, bins, patches = P.hist(x, bins, normed=1, histtype='bar', rwidth=0.8)
+
+#
+# now we create a cumulative histogram of the data
+#
+P.figure()
+
+n, bins, patches = P.hist(x, 50, normed=1, histtype='step', cumulative=True)
+P.setp(patches, 'facecolor', 'b', 'alpha', 0.75)
+
+# add a line showing the expected distribution
+y = P.normpdf( bins, mu, sigma).cumsum()
+y /= y[-1]
+l = P.plot(bins, y, 'k--', linewidth=1.5)
+
+# create a second data-set with a smaller standard deviation
+sigma2 = 15.
+x = mu + sigma2*P.randn(10000)
+
+n, bins, patches = P.hist(x, bins=bins, normed=1, histtype='step', 
cumulative=True)
+P.setp(patches, 'facecolor', 'r', 'alpha', 0.5)
+
+# add a line showing the expected distribution
+y = P.normpdf( bins, mu, sigma2).cumsum()
+y /= y[-1]
+l = P.plot(bins, y, 'r--', linewidth=1.5)
+
+P.grid(True)
+P.ylim(0, 1.05)
+
+
+#
+# histogram has the ability to plot multiple data in parallel ...
+#
+P.figure()
+
+# create a new data-set
+x = mu + sigma*P.randn(1000,3)
+
+n, bins, patches = P.hist(x, 10, normed=1, histtype='bar')
+
+#
+# ... or we can stack the data
+#
+P.figure()
+
+n, bins, patches = P.hist(x, 10, normed=1, histtype='barstacked')
+
+
+P.show()
\ No newline at end of file

Deleted: trunk/matplotlib/examples/pylab/histogram_demo_step.py
===================================================================
--- trunk/matplotlib/examples/pylab/histogram_demo_step.py      2008-05-22 
21:49:25 UTC (rev 5220)
+++ trunk/matplotlib/examples/pylab/histogram_demo_step.py      2008-05-23 
07:51:20 UTC (rev 5221)
@@ -1,31 +0,0 @@
-#!/usr/bin/env python
-from pylab import *
-
-mu, sigma = 100, 15
-x = mu + sigma*randn(10000)
-
-# the histogram of the data
-n, bins, patches = hist(x, 50, normed=1, histtype='step')
-setp(patches, 'facecolor', 'g', 'alpha', 0.75)
-
-# add a 'best fit' line
-y = normpdf( bins, mu, sigma)
-l = plot(bins, y, 'k--', linewidth=1)
-
-
-# overlay the first histogram with a second one
-# were the data has a smaller standard deviation
-mu, sigma = 100, 5
-x = mu + sigma*randn(10000)
-
-n, bins, patches = hist(x, 50, normed=1, histtype='step')
-setp(patches, 'facecolor', 'r', 'alpha', 0.25)
-
-y = normpdf( bins, mu, sigma)
-l = plot(bins, y, 'k--', linewidth=1)
-
-axis([40, 160, 0, 0.09])
-grid(True)
-
-#savefig('histogram_demo',dpi=72)
-show()

Modified: trunk/matplotlib/lib/matplotlib/axes.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/axes.py     2008-05-22 21:49:25 UTC (rev 
5220)
+++ trunk/matplotlib/lib/matplotlib/axes.py     2008-05-23 07:51:20 UTC (rev 
5221)
@@ -5392,7 +5392,8 @@
         right
         """
 
-        ax2 = self.figure.add_axes(self.get_position(True), sharex=self, 
frameon=False)
+        ax2 = self.figure.add_axes(self.get_position(True), sharex=self,
+            frameon=False)
         ax2.yaxis.tick_right()
         ax2.yaxis.set_label_position('right')
         self.yaxis.tick_left()
@@ -5408,7 +5409,8 @@
         top
         """
 
-        ax2 = self.figure.add_axes(self.get_position(True), sharey=self, 
frameon=False)
+        ax2 = self.figure.add_axes(self.get_position(True), sharey=self,
+            frameon=False)
         ax2.xaxis.tick_top()
         ax2.xaxis.set_label_position('top')
         self.xaxis.tick_bottom()
@@ -5420,16 +5422,19 @@
 
     def hist(self, x, bins=10, normed=False, cumulative=False,
              bottom=None, histtype='bar', align='edge',
-             orientation='vertical', width=None, log=False, **kwargs):
+             orientation='vertical', rwidth=None, log=False, **kwargs):
         """
         HIST(x, bins=10, normed=False, cumulative=False,
              bottom=None, histtype='bar', align='edge',
-             orientation='vertical', width=None, log=False, **kwargs)
+             orientation='vertical', rwidth=None, log=False, **kwargs)
 
         Compute the histogram of x.  bins is either an integer number of
         bins or a sequence giving the bins.  x are the data to be binned.
+        x can be an array or a 2D array with multiple data in its columns.
 
-        The return values is (n, bins, patches)
+        The return values is (n, bins, patches) or
+        ([n0,n1,...], bins, [patches0,patches1,...]) if the input
+        contains multiple data.
 
         If normed is true, the first element of the return tuple will
         be the counts normalized to form a probability density, ie,
@@ -5442,22 +5447,25 @@
 
         If cumulative is True then a histogram is computed where each bin
         gives the counts in that bin plus all bins for smaller values.
-        The last bins gives the total number of datapoints.  If normed is
+        The last bin gives the total number of datapoints.  If normed is
         also True then the histogram is normalized such that the last bin
         equals one.
 
-        histtype = 'bar' | 'step'. The type of histogram to draw.
-        'bar' is a traditional bar-type histogram, 'step' generates
-        a lineplot.
+        histtype = 'bar' | 'barstacked' | 'step'. The type of histogram
+        to draw.  'bar' is a traditional bar-type histogram, 'barstacked'
+        is a bar-type histogram where multiple data are stacked on top
+        of each other, and 'step' generates a lineplot.
 
-        align = 'edge' | 'center'.  Interprets bins either as edge
-        or center values
+        align controles how the histogram is plotted
+         - 'edge'  : bars are centered between the bin edges
+         - 'center': bars are centered on the left bin edges
 
         orientation = 'horizontal' | 'vertical'.  If horizontal, barh
         will be used and the "bottom" kwarg will be the left edges.
 
-        width: the width of the bars.  If None, automatically compute
-        the width. Ignored for 'step' histtype.
+        rwidth: the relative width of the bars as fraction of the bin
+        width.  If None, automatically compute the width. Ignored
+        for 'step' histtype.
 
         log: if True, the histogram axis will be set to a log scale
 
@@ -5466,25 +5474,86 @@
         %(Rectangle)s
         """
         if not self._hold: self.cla()
-        n, bins = np.histogram(x, bins, range=None,
-            normed=bool(normed), new=True)
 
+        if kwargs.get('width') is not None:
+            raise DeprecationWarning(
+                'hist now uses the rwidth to give relative width and not 
absolute width')
+
+        # todo: make hist() work with list of arrays with different lengths
+        x = np.asarray(x)
+        if len(x.shape)==2:
+            n = []
+            for i in xrange(x.shape[1]):
+                # this will automatically overwrite bins,
+                # so that each histogram uses the same bins
+                m, bins = np.histogram(x[:,i], bins, range=None,
+                    normed=bool(normed), new=True)
+                n.append(m)
+        else:
+            n, bins = np.histogram(x, bins, range=None,
+                normed=bool(normed), new=True)
+            n = [n,]
+        
         if cumulative:
             if normed:
-                n = (n * np.diff(bins)).cumsum()
+                n = [(m * np.diff(bins)).cumsum() for m in n]
             else:
-                n = n.cumsum()
+                n = [m.cumsum() for m in n]
 
-        if histtype == 'bar':
-            if width is None:
-                width = 0.9*(bins[1]-bins[0])
+        ccount = 0
+        colors = _process_plot_var_args.defaultColors[:]
+        patches = []
 
+        if histtype.startswith('bar'):
+            totwidth = np.diff(bins)
+            stacked = False
+
+            if rwidth is not None: dr = min(1., max(0., rwidth))
+            elif len(n)>1: dr = 0.8
+            else: dr = 1.0
+
+            if histtype=='bar':
+                width = dr*totwidth/len(n)
+                dw = width
+
+                if len(n)>1:
+                    boffset = -0.5*dr*totwidth*(1.-1./len(n))
+                else:
+                    boffset = 0.0
+            elif histtype=='barstacked':
+                width = dr*totwidth
+                boffset, dw = 0.0, 0.0
+
+                stacked = True
+                if bottom is None: bottom = 0.0
+            else:
+                raise ValueError, 'invalid histtype: %s' % histtype
+
+            if align=='edge':
+                boffset += 0.5*totwidth
+            elif align != 'center':
+                raise ValueError, 'invalid align: %s' % align
+
             if orientation == 'horizontal':
-                patches = self.barh(bins[:-1], n, height=width, left=bottom,
-                                    align=align, log=log)
+                for m in n:
+                    color = colors[ccount % len(colors)]
+                    patch = self.barh(bins[:-1]+boffset, m, height=width,
+                                      left=bottom, align='center', log=log,
+                                      color=color)
+                    patches.append(patch)
+                    if stacked: bottom += m
+                    boffset += dw
+                    ccount += 1
             elif orientation == 'vertical':
-                patches = self.bar(bins[:-1], n, width=width, bottom=bottom,
-                                    align=align, log=log)
+                for m in n:
+                    color = colors[ccount % len(colors)]
+                    patch = self.bar(bins[:-1]+boffset, m, width=width,
+                                     bottom=bottom, align='center', log=log,
+                                     color=color)
+                    patches.append(patch)
+                    if stacked: bottom += m
+                    boffset += dw
+                    ccount += 1
             else:
                 raise ValueError, 'invalid orientation: %s' % orientation
 
@@ -5493,22 +5562,29 @@
             y = np.zeros( 2*len(bins), np.float_ )
 
             x[0::2], x[1::2] = bins, bins
-            y[1:-1:2], y[2::2] = n, n
 
             if align == 'center':
                 x -= 0.5*(bins[1]-bins[0])
+            elif align != 'edge':
+                raise ValueError, 'invalid align: %s' % align
 
-            if orientation == 'horizontal':
-                x,y = y,x
-            elif orientation != 'vertical':
-                raise ValueError, 'invalid orientation: %s' % orientation
-            patches = self.fill(x,y)
+            for m in n:
+                y[1:-1:2], y[2::2] = m, m
+                if orientation == 'horizontal':
+                    x,y = y,x
+                elif orientation != 'vertical':
+                    raise ValueError, 'invalid orientation: %s' % orientation
+                patches.append( self.fill(x,y) )
         else:
             raise ValueError, 'invalid histtype: %s' % histtype
-
-        for p in patches:
-            p.update(kwargs)
-        return n, bins, cbook.silent_list('Patch', patches)
+        
+        for patch in patches:
+            for p in patch:
+                p.update(kwargs)
+        if len(n)==1:
+            return n[0], bins, cbook.silent_list('Patch', patches[0])
+        else:
+            return n, bins, cbook.silent_list('Lists of Patches', patches)
     hist.__doc__ = cbook.dedent(hist.__doc__) % martist.kwdocd
 
     def psd(self, x, NFFT=256, Fs=2, Fc=0, detrend=mlab.detrend_none,


This was sent by the SourceForge.net collaborative development platform, the 
world's largest Open Source development site.

-------------------------------------------------------------------------
This SF.net email is sponsored by: Microsoft
Defy all challenges. Microsoft(R) Visual Studio 2008.
http://clk.atdmt.com/MRT/go/vse0120000070mrt/direct/01/
_______________________________________________
Matplotlib-checkins mailing list
Matplotlib-checkins@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-checkins

Reply via email to