Reputation:
I would like to put text in the right bottom corner of equal aspect figure. I set the position relative to the figure by ax.transAxes, but I have to define the relative coordinate value manually depending on height scales of each figures.
What would be a good way to know axes height scale and the correct text position within the script?
ax = plt.subplot(2,1,1)
ax.plot([1,2,3],[1,2,3])
ax.set_aspect('equal')
ax.text(1,-0.15, 'text', transform=ax.transAxes, ha='right', fontsize=16)
print ax.get_position().height
ax = plt.subplot(2,1,2)
ax.plot([10,20,30],[1,2,3])
ax.set_aspect('equal')
ax.text(1,-0.15, 'text', transform=ax.transAxes, ha='right', fontsize=16)
print ax.get_position().height
Upvotes: 23
Views: 26964
Reputation: 284980
Use annotate
.
In fact, I hardly ever use text
. Even when I want to place things in data coordinates, I usually want to offset it by some fixed distance in points, which is much easier with annotate
.
As a quick example:
import matplotlib.pyplot as plt
fig, axes = plt.subplots(nrows=2, subplot_kw=dict(aspect=1))
axes[0].plot(range(1, 4))
axes[1].plot(range(10, 40, 10), range(1, 4))
for ax in axes:
ax.annotate('Test', xy=(1, 0), xycoords='axes fraction', fontsize=16,
horizontalalignment='right', verticalalignment='bottom')
plt.show()
If you'd like it slightly offset from the corner, you can specify an offset through the xytext
kwarg (and textcoords
to control how the values of xytext
are interpreted). I'm also using the ha
and va
abbreviations for horizontalalignment
and verticalalignment
here:
import matplotlib.pyplot as plt
fig, axes = plt.subplots(nrows=2, subplot_kw=dict(aspect=1))
axes[0].plot(range(1, 4))
axes[1].plot(range(10, 40, 10), range(1, 4))
for ax in axes:
ax.annotate('Test', xy=(1, 0), xycoords='axes fraction', fontsize=16,
xytext=(-5, 5), textcoords='offset points',
ha='right', va='bottom')
plt.show()
If you're trying to place it below the axes, you can use the offset to place it a set distance below in points:
import matplotlib.pyplot as plt
fig, axes = plt.subplots(nrows=2, subplot_kw=dict(aspect=1))
axes[0].plot(range(1, 4))
axes[1].plot(range(10, 40, 10), range(1, 4))
for ax in axes:
ax.annotate('Test', xy=(1, 0), xycoords='axes fraction', fontsize=16,
xytext=(0, -15), textcoords='offset points',
ha='right', va='top')
plt.show()
Also have a look at the Matplotlib annotation guide for more information.
Upvotes: 59