如何在 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()
輸出
廣告