簡體   English   中英

如何向 Matplotlib 中的軸添加具有不同字體大小的“輔助”標簽?

[英]How can I add "secondary" labels with different font sizes to axes in Matplotlib?

我試圖在Matplotlib中生成下圖:

在此處輸入圖像描述

用於生成軸的代碼(沒有標簽):

import matplotlib.pyplot as plt
fig,ax = plt.subplots(3,3,sharex=True,sharey=True,
                      constrained_layout=False)

我知道如何在此處添加標簽“X 軸 label”和“在此處 Y 軸 label”,但我不確定如何放置標簽“A”、“B”、“C”、“D”、 E”和“F”,如上圖所示。 這些標簽的字體大小也應與“此處為 X 軸 label”和“此處為 Y 軸 label”。 有什么建議么?

一般的方法是使用ax.annotate()但對於 x 軸,我們可以簡單地使用子圖標題:

import matplotlib.pyplot as plt
fig, ax = plt.subplots(3,3,sharex=True,sharey=True,
                      constrained_layout=False, figsize=(10, 6))

x_titles = list("DEF")
y_titles = list("ABC")
for curr_title, curr_ax in zip(x_titles, ax[0, :]):
    curr_ax.set_title(curr_title, fontsize=15)
for curr_title, curr_ax in zip(y_titles, ax[:, 0]):
    #the xy coordinates are in % axes from the lower left corner (0,0) to the upper right corner (1,1)
    #the xytext coordinates are offsets in pixel to prevent 
    #that the text moves in relation to the axis when resizing the window
    curr_ax.annotate(curr_title, xy=(0, 0.5), xycoords="axes fraction", 
                     xytext=(-80, 0), textcoords='offset pixels',
                     fontsize=15, rotation="vertical")
plt.show()

樣本 output: 在此處輸入圖像描述

暫無
暫無

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

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