将numpy数组绘制为直方图

时间:2017-04-06 20:09:21

标签: python numpy matplotlib

我使用以下代码将numpy数组绘制为直方图。我最终得到的只是一个盒子。

from sys import argv as a
import numpy as np
import matplotlib.pyplot as plt

r = list(map(int, (a[1], a[2], a[3], a[4], a[5])))
s = np.array([int((x - min(r))/(max(r) - min(r)) * 10) for x in r])
plt.hist(s, normed=True, bins=5)
plt.show()

使用以下输入运行程序 22 43 11 34 26

如何获得直方图,y轴代表列表元素的高度。

2 个答案:

答案 0 :(得分:4)

您可以使用plt.bar

plt.bar(np.arange(len(s)),s)
plt.show()

哪个变成了下面的内容。这是你的预期产量吗?

enter image description here

答案 1 :(得分:2)

您无法获得y轴表示列表元素值的直方图。

根据定义,直方图给出了属于某些箱子的元素数量,或者在某个箱子中找到元素的概率。 plt.hist是绘制函数,用于从这样的直方图中绘制条形图。

因此,当您调用plt.hist(s, normed=True, bins=5)时会发生的情况是,规范化的输入数组s = [ 3, 10, 0, 7, 4]被分为0到10之间的5个区间。s中只有一个数字落入每个区间,所以hisogram图中的所有条形都有相同的高度。

enter image description here

因为在这种情况下你实际上根本不想要直方图,只有条形图的值,你应该使用plt.bar数组s作为高度参数和一些索引作为位置。

from __future__ import division
import numpy as np
import matplotlib.pyplot as plt

a = ["some file", "22", "43", "11","34", "26"]

r = list(map(int, (a[1], a[2], a[3], a[4], a[5])))
s = np.array([int((x - min(r))/(max(r) - min(r)) * 10) for x in r])

plt.bar(np.arange(len(s)), s)
plt.show()

enter image description here