python - 来自数组的直方图 matplotlib

标签 python arrays matplotlib

我有两个数组:

例如:

a=[1, 2, 3, 4]

b=[10, 20, 30, 40]

根据这些数字,我需要绘制直方图,我知道用 (1,10)、(2, 20) 等坐标绘制曲线很容易。但是如何从数组绘制直方图。目前我坚持选择绘制直方图。任何建议都会很好。

import matplotlib.pyplot as plt
import numpy as np

a = [([97, 99, 99, 96, 97, 98, 99, 97, 99, 99, 96, 97, 99, 99, 95,
       98, 99, 97, 97, 98, 97, 96, 98, 98, 98, 98, 98, 98, 96, 98, 98, 98, 98,
       98, 98, 96, 97, 97, 97, 97, 97, 96, 96, 97, 97, 96, 95, 97, 96, 97, 96, 97,
       96, 95, 96, 97, 95, 95, 93, 93, 92, 93, 93, 95, 95, 94, 93, 94, 94, 95, 95, 95,
       95, 96, 96, 95, 96, 96, 96, 96, 94, 95, 90, 95, 95, 95, 95,
       95, 88, 94, 94, 93, 95, 95, 94, 95, 95, 95, 95, 95, 93],)]

for item in a[0]:
    s = item

lengths = len(s)
s2 = [s[x:x+9] for x in xrange(0, len(s), 9)]
print s2.index(min(s2))

test = 2400+int(lengths)
xaxis=range(2400,test)
yaxis=s

下面是图像示例 x 轴是 2400-2500 的值,y 轴是某种数组的值。

enter image description here

最佳答案

您可以使用 matplotlib.pyplot.hist 在 matplotlib 中制作直方图.鉴于问题中的代码,您希望 a 中的值是 2400 到 2500 之间的值的频率,这可以像这样做一样简单:

plt.hist(range(2400, 2501), weights=a[0][0])
plt.show()

这样做会根据 a 使用默认的 10 个 bin 生成直方图,如下所示。

Histogram with ten bins.

然而,这里有一点奇怪,因为 a 有 101 个值(意味着绘制的范围是 2400 到 2500,包括在内),所以最后一个 bin 得到十一个值的频率计数,而其他箱子获得十个值的频率计数。您可以使用以下内容为每个值指定自己的 bin。

plt.hist(range(2400, 2501), weights=a[0][0], bins=101)
plt.show()

生成下图。

Histogram with 101 bins.

关于python - 来自数组的直方图 matplotlib,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8553573/

相关文章:

python - 从 seaborn 中保存情节

python - 执行源代码时忽略 ImportError

python - 如何通过值知道散列中的键?

php - 使用mysql insert id和if语句插入数组数据

php - 如何在 phpstorm 中为数组声明强制执行长语法?

numpy - 如何可视化或绘制多维张量?

python - 在 Pandas 中使用 iloc 的正确方法

python - 我如何决定在 mac 终端中打开哪个 python?

python : Calculate the eucledean distances from one coordinates to a array with coordinates

python - Pyplot - 在限制 x 轴后重新缩放 y 轴