说我有两个数组:
x=np.random.uniform(0,10,100)
y=np.random.uniform(0,1,100)
我想在xmin = 0和xmax = 10之间建立n个容器。对于每个y,都有一个对应的x属于这些n个仓位之一。假设与每个仓对应的值最初为零。我想做的是将y的每个值添加到其对应的x箱中,并绘制一个直方图,其中x轴为xmin到nmax箱的xmax,y轴为添加到相应x箱中的所有y值的总和。如何在python中做到这一点?
答案 0 :(得分:0)
首先,我认为使用条形图而不是直方图会更容易。
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()
如果您听不懂某事,请告诉我,以便对其进行解释