如何使用 Matplotlib 來更改座標軸的刻度的字型大小?


若要更改 Matplotlib 中座標軸物件的刻度字型大小,我們可以採取以下步驟:

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

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

  • 使用 plot() 方法繪製 x 和 y 資料點,顏色為紅色且線寬為 5。

  • 使用 x 資料點設定 xticks 

  • 使用 get_major_ticks() 方法獲取主要刻度列表。

  • 迭代主要刻度(從步驟 5 開始),並設定字型大小,將其旋轉 45 度。

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

示例

import numpy as np
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
x = np.linspace(-2, 2, 10)
y = np.sin(x)

fig, ax = plt.subplots()

ax.plot(x, y, c='red', lw=5)
ax.set_xticks(x)
for tick in ax.xaxis.get_major_ticks():
   tick.label.set_fontsize(14)
   tick.label.set_rotation('45')

plt.tight_layout()

plt.show()

輸出

更新日期:08-May-2021

527 次瀏覽

開啟您的 職業生涯

透過完成課程獲取認證

開始
廣告