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

Cách thêm colorbar cho hist2d plot trong Matplotlib

hist2d trả về tuple, phần tử thứ 4 (index 3) là QuadMesh (scalar mappable) dùng cho colorbar.

  • x, y = random normal.
  • fig, ax = subplots().
  • hh = ax.hist2d(x, y, bins=40, norm=colors.LogNorm()).
  • fig.colorbar(hh[3], ax=ax).
  • show().

Ví dụ

import numpy as np
from matplotlib import pyplot as plt, colors
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
x = np.random.randn(100)
y = np.random.randn(100) + 5
fig, ax = plt.subplots()
hh = ax.hist2d(x, y, bins=40, norm=colors.LogNorm())
fig.colorbar(hh[3], ax=ax)
plt.show()

Kết quả

Histogram 2D (heatmap) log-scale với colorbar bên phải.