[英]Python/Matplotlib - How to put text in the corner of equal aspect figure
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.
我通过ax.transAxes设置相对于图形的位置,但是我必须根据每个图形的高度尺度手动定义相对坐标值。
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
Use annotate
. 使用
annotate
。
In fact, I hardly ever use text
. 事实上,我几乎没有使用过
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
. 即使我想将数据放置在数据坐标中,我通常也希望将它偏移一些固定的点距离,这对于
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). 如果你想从角落略微偏移,你可以通过
xytext
kwarg指定偏移量(和textcoords
来控制如何解释xytext
的值)。 I'm also using the ha
and va
abbreviations for horizontalalignment
and verticalalignment
here: 我也在这里使用
ha
和va
缩写来进行horizontalalignment
和verticalalignment
:
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. 另请参阅Matplotlib注释指南以获取更多信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.