Matplotlib: Plot binned data
In Matplotlib, you can use hist and hist2d to make 1D & 2D histograms. These functions take unbinned data as input, do the binning, and then plot the histograms. (They are based on Numpy histogram and histogram2d.) In HEP, we often work directly with binned data (i.e. histograms), but there is no available function in Matplotlib that takes histograms and plot them.
I found that the rootpy project has implemented methods to plot ROOT histograms using Matplotlib. For example, this uses Matplotlib
hist2d to plot a ROOT 2D histogram.
Based on the example, I wrote some simple functions that take binned data that exist as a Numpy array and plot it using Matplotlib
def hist_on_binned_data(hist, edges, ax=None, **kwargs): from matplotlib.pyplot import gca if ax is None: ax = gca() x = (edges[1:] + edges[:-1]) / 2 h, edges, patches = ax.hist(x, weights=hist, bins=edges, **kwargs) return (h, edges, patches) def hist2d_on_binned_data(hist, xedges, yedges, colorbar=False, ax=None, **kwargs): from matplotlib.pyplot import gca if ax is None: ax = gca() xdata = (xedges[1:] + xedges[:-1]) / 2 ydata = (yedges[1:] + yedges[:-1]) / 2 xv, yv = np.meshgrid(xdata, ydata) x = xv.ravel() y = yv.ravel() z = hist.T.ravel() h, xedges, yedges, image = ax.hist2d(x, y, weights=z, bins=(xedges, yedges), **kwargs) if colorbar: cb = ax.figure.colorbar(image, ax=ax) return (h, xedges, yedges, image)