如何在 Matplotlib 中使用文字註釋熱圖?


若要在 matplotlib 中使用文字註釋熱圖,我們可以採取以下步驟 -

  • 使用4×4維度陣列建立隨機資料。

  • 使用 pcolor() 方法建立一個帶非規則矩形網格的偽彩圖。

  • 若要在畫素中放置文字,我們可以使用 text() 方法。

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

示例

import matplotlib.pyplot as plt
import numpy as np
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
data = np.random.rand(4, 4)
heatmap = plt.pcolor(data, cmap="PuBuGn_r")
for y in range(data.shape[0]):
   for x in range(data.shape[1]):
      plt.text(x + 0.5, y + 0.5, '%.4f' % data[y, x],
         horizontalalignment='center',
         verticalalignment='center',
      )
plt.show()

輸出

更新時間:08-05-2021

1000+ 瀏覽

開啟你的職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.