如何在 Matplotlib 中為 hist2d 圖新增顏色條?


要為hist2d圖新增顏色條,我們可以將標量可對映物件傳遞給 colorbar() 方法的引數。

步驟

  • 使用 numpy 建立 x 和 y 資料點。

  • 使用subplots()方法建立一個圖形和一組子圖。

  • 使用 hist2d()方法建立二維直方圖。

  • 建立一個用於 hist2d 標量可對映例項的顏色條。

  • 要顯示圖形,請使用show()方法。

示例

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()

輸出

更新於: 2021 年 5 月 11 日

4 千次瀏覽

開啟你的 事業

完成課程以獲得認證

開始學習
廣告
© . All rights reserved.