将numpy数组绘制为直方图

2024-04-18 19:08:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我有下面的代码,用来绘制一个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轴表示列表元素高度的直方图。


Tags: 代码fromimportnumpyasnpsys绘制
2条回答

您可以使用^{}

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

它变成了下面。这是你的预期产量吗?

enter image description here

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

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

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

enter image description here

因为在这种情况下,实际上根本不需要直方图,而只需要值的条形图,所以应该使用^{}和数组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

相关问题 更多 >