3
votes

Say I have an array of bin edges, and an array of bin values. (basically the output of plt.hist). For instance:

bins = np.array([1, 2, 3, 4, 5])
vals = np.array([2, 5, 5, 2])

How do I plot this as a histogram?

Edit: for clarity, I mean vals to be the "height" of each bin, where len(vals) + 1 = len(bins)

2

2 Answers

3
votes

If you are using python 3.5 you can use pyplot fill_between function for such. You can use following code:

import numpy as np
import matplotlib.pyplot as plt
bins = np.array([1, 2, 3, 4, 5])
vals = np.array([2, 5, 5, 2])

plt.fill_between(bins,np.concatenate(([0],vals)), step="pre")
plt.show()

This will generate below graph: graph with step command

2
votes

You can use a bar plot:

enter image description here

bins = np.array([1, 2, 3, 4, 5])
vals = np.array([2, 5, 5, 2])
plt.bar((bins[1:] + bins[:-1]) * .5, vals, width=(bins[1] - bins[0]))
plt.show()

The trick is to use the midpoints of your "edges" (bins[1:] + bins[:-1]) * .5, and setting the width as (bins[1] - bins[0]) assuming that you have constant widths for your entire histogram.