python - 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 中做到这一点?
解决方案
首先,我认为使用条形图而不是直方图更容易。
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()
如果您有不明白的地方,请告诉我,以便解释
推荐阅读
- python - 为什么pygame不继续循环?
- android - Google Play Console 阻止生产自动发布
- r - 在循环的 ggplot 中定义 xlim 并可视化重叠变量
- sh - dd:复制每个 M 大小块的 N 个首字节
- css - 在最终图像上停止 CSS 动画的问题
- vue.js - 当设备将方向更改为横向时,如何防止我的应用旋转?
- angular - 如何在 Angular 中的 DataSource 对象中将路径设置为 DataSource 属性名称 - EJ2 树视图
- python-3.x - python中的随机函数在圆圈内生成随机对
- typescript - Typescript 重载函数签名中的错误
- java - 自定义 DiscoveryClient 用于发现 Spring Cloud Config 服务器