GeauxEric
GeauxEric

Reputation: 3050

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

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.

Upvotes: 8

Views: 21142

Answers (4)

Avi Vajpeyi
Avi Vajpeyi

Reputation: 698

Matplotlib (version 3.4.2) has a function to help with this: pyplot.subplot_mosaic.

See the example here which demonstrates how to produce the following: enter image description here

Upvotes: 0

flamo
flamo

Reputation: 1

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

Upvotes: 0

Simas Glinskis
Simas Glinskis

Reputation: 91

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

Upvotes: 9

Hooked
Hooked

Reputation: 88118

You can use annotate, but you'll need to set the correct limits so they are in the "upper right corner". 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.

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

enter image description here

It's also worth looking at the other ways to put text on the figure.

Upvotes: 9

Related Questions