在 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') for t in legend.get_texts(): t.set_ha('left') plt.show()
輸出
廣告