Add bin/sawsim_plot_histogram_file.py and Histogram.plot().
[sawsim.git] / pysawsim / histogram.py
index acd135955e1223df0a0b0f591ceb8849cee54230..cdb0bbf086120789595bf4061969d3f1fd73b814 100644 (file)
 """Histogram generation and comparison.
 """
 
+import matplotlib
+matplotlib.use('Agg')  # select backend that doesn't require X Windows
 import numpy
+import pylab
 
 from . import log
 
@@ -29,6 +32,11 @@ _multiprocess_can_split_ = True
 """Allow nosetests to split tests between processes.
 """
 
+FIGURE = pylab.figure()  # avoid memory problems.
+"""`pylab` keeps internal references to all created figures, so share
+a single instance.
+"""
+
 
 class Histogram (object):
     """A histogram with a flexible comparison method, `residual()`.
@@ -243,3 +251,14 @@ class Histogram (object):
         """
         r_method = getattr(self, self._type_to_method(type))
         return r_method(other)
+
+    def plot(self, title=None, filename=None):
+        FIGURE.clear()
+        axes = FIGURE.add_subplot(1, 1, 1)
+        axes.hist(x=self.bin_edges[:-1],  # one fake entry for each bin
+                  weights=self.counts,    # weigh the fake entries by count
+                  bins=self.bin_edges,
+                  align='mid', histtype='stepfilled')
+        axes.set_title(title)
+        pylab.show()
+        FIGURE.savefig(filename)