簡體   English   中英

在matplotlib中為subplot添加標簽

[英]add label to subplot in matplotlib

是否有自動方式將純標簽添加到子圖中? 具體來說,我用過

ax1 = fig.add_subplot(121)
ax2 = fig.add_subplot(122)

我想在子圖中的右上角添加“A”和“B”以區分它們,現在我正在使用虛擬方式之類的東西

ax1.annotate('A', xy=(2, 1), xytext=(1, 22))
ax2.annotate('B', xy=(2, 1), xytext=(1, 22))

我試過用

ax1.legend()

這也給了我在字母之前的線條或點的“小圖像”,我不需要那個圖像。

您可以使用annotate ,但是您需要設置正確的限制,以便它們位於“右上角”。 如果在完成所有繪圖后調用annotate命令,這應該可以工作,因為它從軸本身拉出限制。

import pylab as plt

fig = plt.figure()
ax1 = fig.add_subplot(121)
ax2 = fig.add_subplot(122)

def get_axis_limits(ax, scale=.9):
    return ax.get_xlim()[1]*scale, ax.get_ylim()[1]*scale

ax1.annotate('A', xy=get_axis_limits(ax1))
ax2.annotate('B', xy=get_axis_limits(ax2))
plt.show()

在此輸入圖像描述

同樣值得研究將文字放在圖上的其他方法

你可以跳過編寫一個輔助函數,然后調用:

ax1 = fig.add_subplot(121)
ax2 = fig.add_subplot(122)

ax1.annotate("A", xy=(0.9, 0.9), xycoords="axes fraction")
ax2.annotate("B", xy=(0.9, 0.9), xycoords="axes fraction")

通過鈎子作品回答,但請記住,你需要正確地縮放位置。

def text_coords(ax=None,scalex=0.9,scaley=0.9):
  xlims = ax.get_xlim()
  ylims = ax.get_ylim()
  return {'x':scalex*np.diff(xlims)+xlims[0],
        'y':scaley*np.diff(ylims)+ylims[0]}


scalex = [0.02,0.02,0.75,0.75]
scaley = [0.02,0.75,0.02,0.75]
labels = ['(a)','(b)','(c)','(d)']

f,ax = plt.subplots(2,2)
for sx,sy,a,l in zip(scalex,scaley,np.ravel(ax),labels):
   a.text(s=l,**text_coords(ax=a,scalex=sx,scaley=sy))
plt.tight_layout()
plt.show()

標簽演示

暫無
暫無

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

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