每個axes對象都有xaxis和yaxis屬性,且xaxis和yaxis的每一個坐標軸都有主要刻度線/標簽和次要刻度線/標簽組成,標簽位置通過一個Locator對象設置,標簽格式通過一個Formatter設置。
plt.style.use('seaborn-whitegrid')
#x軸和y軸設置成對數顯示尺度
ax = plt.axes(xscale='log', yscale='log')
#主刻度和次刻度標簽位置對象Locator
print(ax.xaxis.get_major_locator())
print(ax.xaxis.get_minor_locator())
<matplotlib.ticker.LogLocator object at 0x0000021BD90A2308>
<matplotlib.ticker.LogLocator object at 0x0000021BD90A2508>
#主刻度和次刻度標簽格式對象Formatter
print(ax.xaxis.get_major_formatter())
print(ax.xaxis.get_minor_formatter())
<matplotlib.ticker.LogFormatterSciNotation object at 0x0000021BD90A24C8>
<matplotlib.ticker.LogFormatterSciNotation object at 0x0000021BD99E97C8>
常用的定位器類和格式生成器類
定位器類 | 描述 |
---|---|
NullLocator | 無刻度 |
FixdeLocator | 刻度位置固定 |
IndexLocator | 用索引作為定位器(如 x = range(len(y)) |
LinearLocator | 從min 到max 均勻分布刻度 |
LogLocator | 從min 到 max 按對數分布刻度 |
MultipleLocator | 刻度和范圍都是基數(base)的倍數 |
MaxNLocator | 為最大刻度找到最優位置 |
AutoLocator | (默認)以MaxNLocator進行簡單配置 |
AutoMinorLocator | 次要刻度的定位器 |
格式生成器類 | 描述 |
---|---|
NullFormatter | 刻度上無標簽 |
IndexFormatter | 將一組標簽設置為字符串 |
FixedFormatter | 手動為刻度設置標簽 |
FuncFormatter | 用自定義函數設置標簽 |
FormatStrFormatter | 為每個刻度值設置字符串格式 |
ScalarFormatter | (默認)為標量值設置標簽 |
LogFormatter | 對數坐標軸的默認格式生成器 |
隱藏刻度和標簽
ax = plt.axes()
ax.plot(np.random.rand(50))
#y軸移除標簽和刻度線
ax.yaxis.set_major_locator(plt.NullLocator())
#x軸移除標簽,保留刻度線
ax.xaxis.set_major_formatter(plt.NullFormatter())
隱藏刻度和標簽后的圖像:
例子:
#創建5 * 5 的 (5 * 5)大小的窗格
fig, ax = plt.subplots(5, 5, figsize=(5, 5))
#行列空白設置為0
fig.subplots_adjust(hspace=0, wspace=0)
#從scikit-learn獲取一些人臉照片數據
from sklearn.datasets import fetch_olivetti_faces
faces = fetch_olivetti_faces().images
for i in range(5):
for j in range(5):
#隱藏x和y軸刻度和標簽
ax[i,j].xaxis.set_major_locator(plt.NullLocator())
ax[i,j].yaxis.set_major_locator(plt.NullLocator())
ax[i,j].imshow(faces[10 * i + j], cmap='bone')
增減刻度數量
fig, ax = plt.subplots(4, 4, sharex=True, sharey=True)
for axi in ax.flat:
#plt.MaxNLocator()設置最多的刻度數量
axi.xaxis.set_major_locator(plt.MaxNLocator(3))
axi.yaxis.set_major_locator(plt.MaxNLocator(3))
設置最多的刻度數量為3:
自定義刻度格式(FuncFormatter)
#畫正弦曲線和余弦曲線
fig, ax = plt.subplots()
x = np.linspace(0, 3 * np.pi, 1000)
ax.plot(x, np.sin(x), lw=3, label='Sine')
ax.plot(x, np.cos(x), lw=3, label='Cosine')
#設置網格
ax.grid(True)
#設置圖例
ax.legend(frameon=False)
#設置坐標軸等距
ax.axis('equal')
#設置x坐標軸上下限
ax.set_xlim(0, 3 * np.pi)
#自定義坐標標簽
#使用美元符號$將LaTex字符串括起來,可以顯示數學符號和公式:$\pi$
def format_func(value, tick_number):
# N * np.pi/2 = value , value為np.pi/2的倍數
N = int(np.round(2 * value / np.pi))
# 0點位置
if N == 0:
return "0"
# np.pi/2 的位置
elif N == 1:
return r"$\pi/2$"
# np.pi/2的位置
elif N == 2:
return r"$\pi$"
# np.pi/2 倍數的位置
elif N % 2 > 0:
return r"${0}\pi/2$".format(N)
# np.pi 倍數的位置
else:
return r"${0}\pi$".format(N // 2)
#plt.FuncFormatter()創建自定義的刻度格式對象
my_formatter = plt.FuncFormatter(format_func)
ax.xaxis.set_major_formatter(my_formatter)
fig