从2d数组python创建直方图

时间:2017-07-12 23:23:25

标签: python pandas numpy matplotlib

目前,我有一个1&0,0&s和-1的矩阵,其中每一行都是一个人,每列都是他们投票的账单。每个单元格中的1,0,1和-1表示他们投票的方式。

我正在尝试构建的直方图将显示Y轴上具有x个投票数量(x量为1' s的行数)的人数。在X轴上,它将有0-N是投票。因此,例如,如果有30人投票赞成,则X轴上30标签处的条形将在Y轴上达到30。

以下是我在MatLab中快速制作的直方图的截图(我的体验就是这样):histograms built in MatLab

我的问题是如何在Python中轻松有效地执行此操作。我对Python的经验很少。

我的代码:

def buildHistogram(matrix):
    plt.hist(matrix, bins = 30)
    plt.show()

产生:histograms built in Python

请告诉我如何将这些分成三个不同的直方图。我需要制作三个不同的阵列吗?

1 个答案:

答案 0 :(得分:2)

我使用了一些随机数据集来重现它:

import numpy as np
import matplotlib.pyplot as plt
arr = np.random.randint(-1, 2, (200, 100))

然后它只是(忽略轴标签和标题):

fig, (ax1, ax2, ax3) = plt.subplots(1, 3)
ax1.hist(np.sum(arr==-1, axis=1), bins=30)  # no
ax2.hist(np.sum(arr==0, axis=1), bins=30)   # nothing
ax3.hist(np.sum(arr==1, axis=1), bins=30)   # yes

这给了我(应该大致是你想要的):

enter image description here

相关问题