Để tạo histogram với các bin diện tích bằng nhau trong matplotlib, thực hiện các bước sau:
Các bước
- Thiết lập kích thước hình và padding.
- Tạo dữ liệu ngẫu nhiên bằng numpy.
- Vẽ histogram với phương thức equal_area làm bin edges để các patch có diện tích bằng nhau.
- Hiển thị hình bằng show().
Ví dụ
import numpy as np
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
def equal_area(x, nbin):
pow = 0.5
dx = np.diff(np.sort(x))
tmp = np.cumsum(dx ** pow)
tmp = np.pad(tmp, (1, 0), 'constant')
return np.interp(np.linspace(0, tmp.max(), nbin + 1), tmp, np.sort(x))
x = np.random.randn(1000)
n, bins, patches = plt.hist(x, equal_area(x, 20), edgecolor='black')
plt.show()
Kết quả
Histogram 20 bin, mỗi bin có diện tích bằng nhau (tần suất tích phân bằng nhau), viền đen.