This is an archival dump of old wiki content --- see scipy.org for current material.
Please see http://scipy-cookbook.readthedocs.org/

Here is an example for creating a 2D histogram with variable bin size and displaying it.

   1 #!/usr/bin/python
   2 import numpy as np
   3 import matplotlib as ml
   4 import matplotlib.pyplot as plt
   5 
   6 
   7 # First we define the bin edges
   8 xedges = [0, 1, 1.5, 3, 5]
   9 yedges = [0, 2, 3, 4, 6]
  10 
  11 # Next we create a histogram H with random bin content
  12 x = np.random.normal(3, 1, 100)
  13 y = np.random.normal(1, 1, 100)
  14 H, xedges, yedges = np.histogram2d(y, x, bins=(xedges, yedges))
  15 
  16 # Or we fill the histogram H with a determined bin content
  17 H = np.ones((4, 4)).cumsum().reshape(4, 4)
  18 print H[::-1]  # This shows the bin content in the order as plotted
  19 
  20 ml.rcParams['image.cmap'] = 'gist_heat'
  21 
  22 
  23 fig = plt.figure(figsize=(6, 3.2))
  24 
  25 # pcolormesh is useful for displaying exact bin edges
  26 ax = fig.add_subplot(131)
  27 ax.set_title('pcolormesh:\nexact bin edges')
  28 X, Y = np.meshgrid(xedges, yedges)
  29 plt.pcolormesh(X, Y, H)
  30 ax.set_aspect('equal')
  31 
  32 
  33 # NonUniformImage can be used for interpolation
  34 ax = fig.add_subplot(132)
  35 ax.set_title('NonUniformImage:\ninterpolated')
  36 im = ml.image.NonUniformImage(ax, interpolation='bilinear')
  37 xcenters = xedges[:-1] + 0.5 * (xedges[1:] - xedges[:-1])
  38 ycenters = yedges[:-1] + 0.5 * (yedges[1:] - yedges[:-1])
  39 im.set_data(xcenters, ycenters, H)
  40 ax.images.append(im)
  41 ax.set_xlim(xedges[0], xedges[-1])
  42 ax.set_ylim(yedges[0], yedges[-1])
  43 ax.set_aspect('equal')
  44 
  45 # Imshow is useful for a simple equidistant representation of bin content
  46 ax = fig.add_subplot(133)
  47 ax.set_title('imshow:\nequitdistant')
  48 im = plt.imshow(H, interpolation='nearest', origin='low',
  49                 extent=[xedges[0], xedges[-1], yedges[0], yedges[-1]])
  50 
  51 
  52 # Finally we add a color bar
  53 cax = fig.add_axes([0.12, 0.1, 0.78, 0.4])
  54 cax.get_xaxis().set_visible(False)
  55 cax.get_yaxis().set_visible(False)
  56 cax.patch.set_alpha(0)
  57 cax.set_frame_on(False)
  58 plt.colorbar(orientation='horizontal', ax=cax)
  59 plt.tight_layout()
  60 plt.show()

histogram2d.png


CategoryCookbookMatplotlib CategoryCookbook

SciPy: Cookbook/Histograms (last edited 2015-10-24 17:48:23 by anonymous)