[英]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?
Say I have two arrays:假设我有两个数组:
x=np.random.uniform(0,10,100)
y=np.random.uniform(0,1,100)
I want to make n bins between xmin=0 and xmax=10.我想在 xmin=0 和 xmax=10 之间制作 n 个 bin。 For each y, there is a corresponding x which belongs to one of these n bins.
对于每个 y,有一个对应的 x 属于这 n 个 bin 之一。 Say the value corresponding to each bin is initially zero.
假设对应于每个 bin 的值最初为零。 What I wish to do is add each value of y to its corresponding x's bin and plot a histogram with the x-axis as xmin to xmax with n bins and the y axis as the total of all y values added to corresponding x's bins.
我希望做的是将 y 的每个值添加到其对应的 x 的 bin 并绘制一个直方图,x 轴为 xmin 到 xmax,n 个 bin,y 轴为添加到相应 x 的 bin 的所有 y 值的总和。 How can one do this in python?
如何在 python 中做到这一点?
First of all, i think its easier to use a bar plot instead of a histogram.首先,我认为使用条形图而不是直方图更容易。
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()
If you don't understand something please tell me, in order to explain it如果你不明白什么,请告诉我,以便解释
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.