I am trying to get a histogram with already binned data. I have been trying to use bar()
for this, but I can\'t seem to figure out how to make it a stepped hist
The simplest solution is to convert your binned dataset to an un-binned, weighted dataset (with number of elements == number of bins). The unbinned dataset would consist of data values equal to the bin centres and weights equal to the values in each bin. For example let's say that your binned data is,
binedges = [0.0, 1.0, 2.0, 3.0]
ybinned = [11., 22., 33.]
The corresponding weighted dataset would be,
y = [0.5, 1.5, 2.5]
weights = [11., 22., 33.]
Note that the choice to use the bin centre is arbitrary, you could use any point within a bin. Once you have generated the un-binned dataset then you can use the normal matplotlib histogram plotting (i.e. Axes.hist).
An example implementation in python follows:
def plot_binned_data(axes, binedges, data,
*args, **kwargs):
#The dataset values are the bin centres
x = (binedges[1:] + binedges[:-1]) / 2.0
#The weights are the y-values of the input binned data
weights = data
return axes.hist(x, bins=binedges, weights=weights,
*args, **kwargs)
You can now have full access to all of the Axes.Histogram plotting options, including histtype="step"
to create the stepped histogram that you wanted.
An example using this function would be,
import numpy
import matplotlib.pyplot as plt
#Create a dataset
dataset = numpy.random.normal(size=100)
#Bin the dataset
binedges = numpy.linspace(-5.0, 5.0, num=10)
y, binedges = numpy.histogram(dataset, binedges)
#Plot the dataset
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
plot_binned_data(ax, binedges, y, histtype="step")
plt.show()
Hope that helps!