[英]Get center of bins histograms python
我正在使用matplotlib.pyplot
的hist2d
函数,给它输入一些坐标(x,y)
。
在定义直方图之后,我想获得每个 bin 的中心,即每个 bin 的中心坐标。
有没有简单的方法来获得它们?
plt.hist
和plt.hist2d
的返回值包括 bin 边缘,因此取左边缘和右边缘的平均值:
h, xedges, patches = plt.hist(x) xcenters = (xedges[:-1] + xedges[1:]) / 2
h, xedges, yedges, image = plt.hist2d(x, y) xcenters = (xedges[:-1] + xedges[1:]) / 2 ycenters = (yedges[:-1] + yedges[1:]) / 2
请注意,如果愿意,您可以使用 numpy 函数,尽管在这种情况下我发现它的可读性较差:
xcenters = np.mean(np.vstack([xedges[:-1], xedges[1:]]), axis=0)
plt.hist2d
的完整示例:
import matplotlib.pyplot as plt
import numpy as np
x = np.random.random(50)
y = np.random.random(50)
h, xedges, yedges, image = plt.hist2d(x, y, bins=5)
xcenters = (xedges[:-1] + xedges[1:]) / 2
ycenters = (yedges[:-1] + yedges[1:]) / 2
输出:
>>> xedges
# array([0.01568168, 0.21003078, 0.40437988, 0.59872898, 0.79307808, 0.98742718])
>>> xcenters
# array([0.11285623, 0.30720533, 0.50155443, 0.69590353, 0.89025263])
>>> yedges
# array([0.00800735, 0.20230702, 0.39660669, 0.59090636, 0.78520603, 0.97950570])
>>> ycenters
# array([0.10515718, 0.29945685, 0.49375652, 0.68805619, 0.88235586])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.