簡體   English   中英

在子圖中旋轉刻度標簽(Pyplot、Matplotlib、gridspec)

[英]Rotate tick labels in subplot (Pyplot, Matplotlib, gridspec)

我正在嘗試將子圖(使用 GridSpec 創建)的 x 標簽旋轉 45 度。 我試過使用axa.set_xticks()axa.set_xticklabels ,但它似乎不起作用。 谷歌也沒有幫助,因為大多數關於標簽的問題都是關於正常情節,而不是次要情節。

請參閱下面的代碼:

width = 20                                    # Width of the figure in centimeters
height = 15                                   # Height of the figure in centimeters
w = width * 0.393701                            # Conversion to inches
h = height * 0.393701                           # Conversion to inches

f1 = plt.figure(figsize=[w,h])
gs = gridspec.GridSpec(1, 7, width_ratios = [1.5, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0])

axa = plt.subplot(gs[0])
axa.plot(dts, z,'k', alpha=0.75, lw=0.25)
#axa.set_title('...')
axa.set_ylabel('TVDSS ' + '$[m]$', fontsize = '10' )
axa.set_xlabel('slowness 'r'$[\mu s/m]$', fontsize = '10')
axa.set_ylim(245, 260)
axa.set_xlim(650, 700)
axa.tick_params(labelsize=7)
axa.invert_yaxis()
axa.grid()

任何幫助將不勝感激!

您可以通過多種方式做到這一點:

這是使用tick_params一種解決方案:

ax.tick_params(labelrotation=45)

這是另一個使用set_xticklabels解決方案:

ax.set_xticklabels(labels, rotation=45)

是使用set_rotation的第三個解決方案:

for tick in ax.get_xticklabels():
    tick.set_rotation(45)

您可以使用此行設置刻度標簽的旋轉屬性:

plt.setp(axa.xaxis.get_majorticklabels(), rotation=45)

setp是一個實用函數,用於設置多個藝術家的屬性(在本例中為所有刻度標簽)。

順便說一句:matplotlib 中的“正常”和子圖之間沒有區別。 兩者都只是 Axes 對象。 唯一的區別是大小和位置以及它們在同一圖中的數量。

只是想添加我在matplotlib git 討論頁面上找到的另一個解決方案:

ax[your_axis].tick_params(axis='x', rotation=90)

您可以通過傳入特定參數來指定所需的軸。 與公認答案相比,此方法的優勢在於您可以控制此更改應用於哪個軸。 其他參數可以在這里找到

ax[your_axis].tick_params(axis='x', rotation=90) 這是正確答案。 我在我的代碼上試過了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM