Plotting a histogram given bin endpoints and values

前提是你 提交于 2019-12-21 22:08:29

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!