如何在 Matplotlib 中更改圖例字型名稱?


要在 matplotlib 中更改圖例字型,我們可以採取以下步驟 −

  • 設定圖形大小並調整子圖之間和周圍的邊距。

  • 使用 numpy 建立 x 資料點。

  • 使用 plot() 方法繪製 x、sin(x)cos(x)

  • 使用 legend() 方法放置圖例。

  • 迭代 legend.get_texts() 並更新圖例字型名稱。

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

示例

import numpy as np
from matplotlib import pyplot as plt

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

x = np.linspace(-5, 5, 100)

plt.plot(x, np.sin(x), label="$y=sin(x)$")
plt.plot(x, np.cos(x), label="$y=cos(x)$")

legend = plt.legend(loc='upper right')

i = 1
for t in legend.get_texts():
   t.set_text("name %d" % i)
   i += 1

plt.show()

輸出

更新於: 2021 年 6 月 4 日

626 次瀏覽

開啟你的 職業生涯

完成課程並獲取認證

開始學習
廣告