【问题标题】:Python bar plot with two arrays带有两个数组的 Python 条形图
【发布时间】:2020-09-29 09:17:20
【问题描述】:

我有两个 numpy 数组 XGX(分别为浮点数和整数),我想对 X 数组进行分箱(因此对应的 GX 值可以保存频率)并绘制带有分箱的直方图在 x 轴上,在 y 轴上频率。我也尝试过使用 pandas 的 qcutcut 和 matplotlib 的 histogram。它们似乎都不起作用。我从头开始用 numpy 创建了 bin 和频率,但我能得到的只是散点图。

bins   = np.linspace(min(X), max(X),100)
freq   = []
countl = 0
for i in range(len(bins)-1):
    count = 0
    for j in range(len(X)):
        if bins[i]<X[j]<bins[i+1]:
            count += np.sum(GX[np.where(X==X[j])])
    freq.append(count)
for j in X:
    if bins[-2]<j<bins[-1]:
        countl += np.sum(GX[np.where(X==j)])

freq.append(countl)
plt.figure(figsize=(7,7))
plt.scatter(bins,freq,c='b')

我怎样才能得到条形图或直方图而不是散点图(可能是更好的分箱方法)?

【问题讨论】:

    标签: python pandas numpy matplotlib seaborn


    【解决方案1】:

    使用您给定的代码,因为您已经计算了每个箱,直方图只是这些箱的条形图:

    plt.bar(bins, freq, width=bins[1]-bins[0], color='crimson', ec='black')
    

    请注意,测试 bins[i] &lt; X[j] &lt; bins[i+1] 会遗漏完全等于 bin 边界的 X 值。在大多数情况下,除了 X 的最小值和最大值之外,这种相等是不太可能的。因此,bins[i] &lt;= X[j] &lt; bins[i+1] 会更安全。此外,为了适应最后一个值,您可以只用一个 epsilon 扩展箱:例如bins = np.linspace(min(X), max(X)+0.000001, 100)(取决于 X 的大小,确保 epsilon 非常小,但在 smaller than 测试中不会被忽略)。

    或者,如果 GX 的总和不会太大而导致内存问题,您可以使用 np.repeat 重复 X 数组,使用 GX 作为重复因子。然后,matplotlib 就可以按照通常的方式计算直方图了:

    all_X = np.repeat(X, GX)
    plt.hist(all_X, bins=100, color='crimson', ec='black')
    

    【讨论】:

      猜你喜欢
      • 2014-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-01
      • 1970-01-01
      • 2019-01-23
      • 2021-10-30
      • 1970-01-01
      相关资源
      最近更新 更多