[英]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.