问题
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)
回答1:
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:
回答2:
You can use a bar plot:
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.
来源:https://stackoverflow.com/questions/44707347/plotting-a-histogram-given-bin-endpoints-and-values