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:UnicodeDecodeError: 'utf-8' 编解码器无法解码位置 0 的字节 0x80:无效的起始字节

python - 以简单且 Python 的方式将简单的字典写入 csv 文件?

c++ - 我可以将 std::vector<int>* 转换为 int* 吗?

python - pandas plot 在 ipython notebook 中不显示为内联

python - Matplotlib 缩放轴长度相等

python - IF-ELIF 语句嵌套

python - 如何使用 Python Selenium 在网站上的内部滚动条上滚动?

java - 为什么 ArrayLists 可以存储不同的对象而数组不能?

javascript - 处理 JMeter WebSocket Sampler 的响应

python - LaTeX 与 Python 3.7 和 Matplotlib