Python/Matplotlib-如何将文本放在等宽图形的角上
我想把文本放在等宽图的右下角。 我通过ax.transAxes设置了相对于图形的位置, 但我必须根据每个图形的高度刻度手动定义相对坐标值 了解轴高度比例和脚本中正确文本位置的好方法是什么Python/Matplotlib-如何将文本放在等宽图形的角上,python,matplotlib,Python,Matplotlib,我想把文本放在等宽图的右下角。 我通过ax.transAxes设置了相对于图形的位置, 但我必须根据每个图形的高度刻度手动定义相对坐标值 了解轴高度比例和脚本中正确文本位置的好方法是什么 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 = 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
使用
注释
事实上,我很少使用文本。甚至当我想把东西放在数据坐标中时,我通常想用点的固定距离来偏移它,这在annotate
中要容易得多
举个简单的例子:
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()
如果您希望它稍微偏离拐角,可以通过xytext
kwarg指定偏移量(和textcoords
来控制xytext
值的解释方式)。我还在这里使用ha
和va
缩写来表示水平对齐
和垂直对齐
:
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()
如果要将其放置在轴下方,可以使用偏移将其放置在点下方的设定距离:
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()
有关更多信息,请参阅。这是一个很好的答案和示例。我将尝试使用注释而不是文本。非常感谢你。