gpt4 book ai didi

python - 使用 matplot 库绘制图形时,直方图的哪一部分引用二维数组的行?

转载 作者:行者123 更新时间:2023-12-01 02:59:52 24 4
gpt4 key购买 nike

我正在使用 matplotlib 来绘制二维 numpy 数组和 bin 的黑白图。在此之前,我只使用两个列表绘制图表。在直方图中,将有三个堆叠条形,对应于数组 a 中的列数。我想知道命令 plt.hist 对数组的行数做了什么?

a= np.arange(12).reshape(4,3)
print a

bins = 5
plt.hist(a, bins, normed=1, histtype='bar',stacked=True)
plt.title('stacked bar')
plt.show()

最佳答案

对答案进行排序:行对应于样本,列对应于变量。

长答案:

直方图将值范围划分为 n 个容器(在示例中为 5 个)。然后,它计算每个 bin 中的值的数量。

为了说明这一点,我们生成 1000 个 0 到 20 之间的随机数:

import numpy as np
a = np.random.randint(0, 20 + 1, 1000)

使用 5 个箱的这些值的直方图将按如下方式定义箱:

bin 1:0 到 4
垃圾箱 2:4 至 8
垃圾箱 3:8 至 12
垃圾箱 4:12 至 16
bin 5:16 至 20

然后,对于每个 bin,它将计算落入相应范围的值的数量。最后,它将每个 bin 中的值数量绘制为条形图:enter image description here

在上面的示例中,我使用了值列表(或一维数组)。如果我们使用二维数组怎么办?然后,对每一列重复上述直方图操作:

b = np.random.randint(0, 21, 3000).reshape(1000, 3)
plt.hist(b, bins=5)

enter image description here

如果设置stacked=True,生成的直方图将绘制在彼此之上:

plt.hist(b, bins=5, stacked=True)

enter image description here

关于python - 使用 matplot 库绘制图形时,直方图的哪一部分引用二维数组的行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43928875/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com