我正在使用的hist2d功能matplotlib.pyplot,給它輸入一些坐標(x,y)。
在定義直方圖之后,我想獲得每個 bin 的中心,即每個 bin 的中心坐標。
有沒有簡單的方法來獲得它們?
uj5u.com熱心網友回復:
plt.hist和的回傳值plt.hist2d包括 bin 邊緣,因此取左邊緣和右邊緣的平均值:
plt.histh, xedges, patches = plt.hist(x) xcenters = (xedges[:-1] xedges[1:]) / 2plt.hist2dh, 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])
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/495129.html
標籤:Python matplotlib 数据集 直方图 直方图2d
