如何绘制直方图,y 轴为 "total of y values corresponding to each x bin",x 轴为 python 中 x 的 n 个 bin?

How to plot a histogram with the yaxis as the "total of y values corresponding to each x bin" and x axis as n bins of x in python?

假设我有两个数组:

x=np.random.uniform(0,10,100)
y=np.random.uniform(0,1,100)

我想在 xmin=0 和 xmax=10 之间创建 n 个 bin。对于每个 y,都有一个对应的 x 属于这 n 个 bin 中的一个。假设对应于每个 bin 的值最初为零。我想做的是将 y 的每个值添加到其对应的 x 的 bin 中,并绘制一个直方图,其中 x 轴为 xmin 到 xmax,n 个 bin,y 轴为添加到相应 x 的 bin 的所有 y 值的总和。如何在 python 中做到这一点?

首先,我认为使用条形图比直方图更容易。

import matplotlib.pyplot as plt
import numpy as np

xmax = 6600
xmin = 6400
x = np.random.uniform(xmin, xmax, 10000)
y = np.random.uniform(0, 1, 10000)
number_of_bins = 100

bins = [xmin]
step = (xmax - xmin)/number_of_bins
print("step = ", step)
for i in range(1, number_of_bins+1):
    bins.append(xmin + step*i)
print("bins = ", bins)

# time to create the sums for each bin
sums = [0] * number_of_bins

for i in range(len(x)):
    sums[int((x[i]-xmin)/step)] += y[i]
print(sums)

xbar = []
for i in range(number_of_bins):
 xbar.append(step/2 + xmin + step*i)
# now i have to create the x axis values for the barplot
plt.bar(xbar, sums, label="Bars")
plt.xlabel("X axis label")
plt.ylabel("Y axis label")
plt.legend()
plt.show()

这是新结果

如果有不明白的地方请告诉我,以便解释