Matplotlib - 設定刻度和刻度標籤



刻度是表示軸上資料點的標記。到目前為止,在所有之前的示例中,Matplotlib 都自動接管了在軸上設定點間距的任務。Matplotlib 的預設刻度定位器和格式化程式旨在在許多常見情況下普遍適用。可以明確提及刻度的位置和標籤以滿足特定要求。

xticks()yticks() 函式以列表物件作為引數。列表中的元素表示將在對應軸上顯示刻度的位置。

ax.set_xticks([2,4,6,8,10])

此方法將使用刻度標記給定位置的資料點。

類似地,可以透過 set_xlabels()set_ylabels() 函式分別設定與刻度標記對應的標籤。

ax.set_xlabels([‘two’, ‘four’,’six’, ‘eight’, ‘ten’])

這將在 x 軸上的標記下方顯示文字標籤。

以下示例演示了刻度和標籤的使用。

import matplotlib.pyplot as plt
import numpy as np
import math
x = np.arange(0, math.pi*2, 0.05)
fig = plt.figure()
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8]) # main axes
y = np.sin(x)
ax.plot(x, y)
ax.set_xlabel(‘angle’)
ax.set_title('sine')
ax.set_xticks([0,2,4,6])
ax.set_xticklabels(['zero','two','four','six'])
ax.set_yticks([-1,0,1])
plt.show()
Tick and Labels
廣告