[英]Python/Matplotlib - How to put text in the corner of equal aspect figure
我想把文字放在相等方面圖的右下角。 我通過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.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
。
事實上,我幾乎沒有使用過text
。 即使我想將數據放置在數據坐標中,我通常也希望將它偏移一些固定的點距離,這對於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
縮寫來進行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()
如果您嘗試將其放置在軸下方,則可以使用偏移量將其放置在點下方的設定距離:
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()
另請參閱Matplotlib注釋指南以獲取更多信息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.