text()为什么我不能根据这个指定 xycoords ?我只想将文本放在图的左上角。但是我不想使用默认的“数据”坐标。错误是:
属性错误:未知属性 xycoords
这是示例代码:
import numpy as np
import math
import matplotlib.pyplot as plt
def f(a,x):
return a*x
def g(a,x):
return 5*a*x
const=[1,2,3]
fig=plt.figure()
ax=fig.add_subplot(1,1,1)
colors=['r','b','g']
labels=[r'$a=1$',r'$a=2$',r'$a=3$']
xArray=np.linspace(0,2,20)
for i in const:
ax.plot(xArray,f(i,xArray),color=colors[i-1],label=labels[i-1])
ax.plot(xArray,g(i,xArray),color=colors[i-1],ls='--')
ax.text(-0.1, 1.1 ,'(a)',size=20,weight='bold',xycoords='axes fraction')
ax.legend(loc=0)
plt.show()
Run Code Online (Sandbox Code Playgroud)
正如 @tcaswell 在评论中所说,xycoords是 的 kwarg annotate,而不是text。
为了实现你想要的,你可以使用transformkwarg. 要使用轴分数坐标,请使用transform = ax.transAxes。
从文档中text:
默认转换指定文本位于数据坐标中,或者,您可以指定轴坐标中的文本(0,0 为左下角,1,1 为右上角)。下面的示例将文本放置在轴的中心:
ax.text(0.5, 0.5,'matplotlib', horizontalalignment='center',
verticalalignment='center',
transform=ax.transAxes)
Run Code Online (Sandbox Code Playgroud)