绘制给定bin端点和值的直方图

时间:2017-06-22 18:56:34

标签: python numpy ipython

假设我有一个bin边缘数组和一个bin值数组。 (基本上是plt.hist的输出)。例如:

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

如何将其绘制为直方图?

编辑:为清楚起见,我的意思是vals是每个bin的“高度”,其中len(vals)+ 1 = len(bin)

2 个答案:

答案 0 :(得分:2)

如果您使用的是python 3.5,则可以使用pyplot fill_between功能。您可以使用以下代码:

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()

这将生成以下图表: graph with step command

答案 1 :(得分:1)

您可以使用bar图:

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()

诀窍是使用“边缘”(bins[1:] + bins[:-1]) * .5的中点,并将宽度设置为(bins[1] - bins[0]),假设您的整个直方图具有恒定的宽度。

相关问题