首页 > 解决方案 > python - 如何绘制一个直方图,其中y轴作为“与每个x bin对应的y值的总和”,x轴作为python中x的n bin?

问题描述

假设我有两个数组:

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 中做到这一点?

标签: pythonpython-3.xhistogram

解决方案


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

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()

这是新的结果

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


推荐阅读