[英]How to edit matplotlib x-tickmarks to match x-labels
我正在嘗試編輯 x 軸上的刻度線和標簽以匹配我正在繪制的數據。 兩個變量(x 和 bin_river)的形狀為 68,因此我想減少繪制的刻度線數量並更改數組 [x] 中第一個和列表編號的標簽。 數組 [x] 看起來像這樣
print(x)
[-30 -29 -28 -27 -26 -25 -24 -23 -22 -21 -20 -19 -18 -17 -16 -15 -14 -13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37]
這些數字幾乎正確地代表了數據。 在數組[x]中,'-30'實際上代表所有數字'<-29','37'代表所有數字'>=37'。 所以我想改變刻度標簽來表示這一點。 我試過
ax.xaxis.set_major_locator(plt.MaxNLocator(15))
ax.set_xticklabels(['<-29','-25','-20', '-15', '-10', '-5', '0', '5', '10', '15', '20', '25', '30', '35', '>=37'],fontsize=11)
ax.plot(x,ar_prob, c=cmap(0.6))
ax.set_title('Atmospheric River Landfall Probability',fontsize=16)
plt.grid(True)
ax.set_xlabel('Blocking Index (dam)',fontsize=15)
ax.set_ylabel('AR Landfall Probability',fontsize=15)
ax.set_ylim(0, 100)
plt.show()
我想要的刻度線沒有繪制並且線放錯了位置。 由於間距發生變化,如何將線擬合到正確的刻度線並在 35 之后添加不規則刻度線?
在設置 xticklabels 時,它有助於設置也顯式設置 xticks。 這樣它們總是對齊的,在縮放時也是如此。
在下面的代碼中,首先將刻度位置設置為 5 的倍數,包括最后一個位置,不要在 35 處放置刻度,因為它太接近了。
然后,標簽的字符串被格式化,第一個和最后一個使用特殊格式。 使用 unicode '≥',因為它更短。
from matplotlib import pyplot as plt
import numpy as np
x = list(range(-30, 38))
ar_prob = np.random.uniform(0, 100, len(x))
fig, ax = plt.subplots()
ax.plot(x, ar_prob, c='crimson')
ticks = [i for i in x if i == x[-1] or (i % 5 == 0 and i < x[-1] - 3)]
tick_labels = [f'<{t}' if t == x[0] else f'≥{t}' if t == x[-1] else f'{t}' for t in ticks]
ax.set_xticks(ticks)
ax.set_xticklabels(tick_labels, fontsize=11)
ax.set_title('Atmospheric River Landfall Probability', fontsize=16)
ax.grid(True)
ax.set_xlabel('Blocking Index (dam)', fontsize=15)
ax.set_ylabel('AR Landfall Probability', fontsize=15)
ax.set_ylim(0, 100)
plt.show()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.