简体   繁体   English

在matplotlib中为subplot添加标签

[英]add label to subplot in matplotlib

Is there an automatic way to add pure labels to the subplots? 是否有自动方式将纯标签添加到子图中? To be specific, I used 具体来说,我用过

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

and I would like to add 'A' and 'B' to the upper right in the subplots to distinguish them, and right now I am using a dummy way something like 我想在子图中的右上角添加“A”和“B”以区分它们,现在我正在使用虚拟方式之类的东西

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

I tried using 我试过用

ax1.legend()

and that also gives me "small images" of lines or dots before the letter and I do not need that image. 这也给了我在字母之前的线条或点的“小图像”,我不需要那个图像。

You can use annotate , but you'll need to set the correct limits so they are in the "upper right corner". 您可以使用annotate ,但是您需要设置正确的限制,以便它们位于“右上角”。 If you call the annotate commands after you've made all the plots, this should work since it pulls the limits from the axis itself. 如果在完成所有绘图后调用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()

在此输入图像描述

It's also worth looking at the other ways to put text on the figure. 同样值得研究将文字放在图上的其他方法

You can skip writing a helper function and just call: 你可以跳过编写一个辅助函数,然后调用:

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")

Answer by hooked works, but keep in mind that you need to scale the position properly. 通过钩子作品回答,但请记住,你需要正确地缩放位置。

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()

labels demo 标签演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM