按轴分数定位文本 [英] Positioning text by axis fraction

查看:39
本文介绍了按轴分数定位文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以通过轴的小数部分在图形中定位文本?无论 x 和 y 的范围如何,我都希望所有绘图的文本都位于相同的位置.此功能在 ax.annotate() 中,但我需要添加额外的 'xy' 参数,这会使我的代码更难阅读.

Is there a way to position text in a figure by the fraction of the axis? I want the text in the same position for all my plots regardless of their differing ranges in x and y. This functionality is in ax.annotate() but I need to put in the extra 'xy' argument which makes my code harder to read.

import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure() 
ax = fig.add_subplot(1, 1, 1)
ax.plot(np.arange(10),12*np.arange(10)) 
ax.annotate('Correct Position', xy=(0, 0), xytext=(0.4, 0.7), textcoords='axes fraction')
ax.text(0.4, 0.7, 'Incorrect Position')

plt.show()

推荐答案

您可以使用 transform 关键字:

You can use the transform keyword:

import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure() 
ax = fig.add_subplot(1, 1, 1)
ax.plot(np.arange(10),12*np.arange(10)) 
ax.text(0.4, 0.7, 'Correct Position', transform=ax.transAxes)

plt.show()

这篇关于按轴分数定位文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆