Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Cách vẽ histogram 2D trong Matplotlib

Histogram 2D (hist2d) cho thấy phân bố tần suất của các cặp giá trị (x, y). Các bước:

  • Thiết lập figure size và padding.
  • Tạo dữ liệu x, y ngẫu nhiên.
  • Tạo figure và subplots.
  • Vẽ histogram 2D bằng hist2d().
  • Đặt tiêu đề.
  • Hiển thị 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

x = 2 * np.random.randn(5000)
y = x + np.random.randn(5000)
fig, ax = plt.subplots()
_ = ax.hist2d(x[::10], y[::10])
ax.set_title('2D Histogram')
plt.show()

Kết quả

Cách vẽ histogram 2D trong Matplotlib