原答案会报错
TypeError Traceback (most recent call last) Cell In[1], line 24
22 y=np.sin(x) 23 ax2.plot(x,y,linestyle='-.',color='purple') ---> 24 ax2.annotate(s='Here I am',xy=(4.8,np.sin(4.8)),xytext=(3.7,-0.2),weight='bold',color='k', 25 arrowprops=dict(arrowstyle='-|>',connectionstyle='arc3',color='red'), 26 bbox=dict(boxstyle='round,pad=0.5',fc='yellow', ec='k',lw=1 ,alpha=0.8)) 27 ax2.set_ylim(-1.5,1.5) 28 ax2.set_xlim(0,10)
TypeError: Axes.annotate() missing 1 required positional argument: 'text'
原因是
在 Matplotlib 里,annotate
函数的第一个参数既可以写成s
,也可以直接以位置参数的形式传入。在你提供的代码中,s
是个关键字参数,不过它在旧版本的 Matplotlib 中使用,而在较新版本里,第一个参数就直接代表text
了,不需要再用s
来指定。
修正后的代码:
import matplotlib.pyplot as plt
import numpy as np
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
%matplotlib inline
fig=plt.figure()
ax1=fig.add_subplot(121)
t=np.arange(0.0,5,0.01)
s=np.sin(2*np.pi*t)
ax1.plot(t,s,lw=2)
bbox=dict(boxstyle='round',fc='white')
plt.annotate('local max',xy=(2.3,1),xytext=(3,1.5),
arrowprops=dict(facecolor='black',edgecolor='red',headwidth=7,width=2),bbox=bbox)
bbox_prop=dict(fc='white')
ax1.set_ylabel('Y',fontsize=12)
ax1.set_xlabel('X',fontsize=12)
ax1.set_ylim(-2,2)
ax1.text(1,1.2,'max',fontsize=18)
ax1.text(1.2,-1.8,'$y=sin(2*np.pi*t)$',bbox=bbox,rotation=10,alpha=0.8)
ax2=fig.add_subplot(122)
x=np.linspace(0,10,200)
y=np.sin(x)
ax2.plot(x,y,linestyle='-.',color='purple')
ax2.annotate('Here I am',xy=(4.8,np.sin(4.8)),xytext=(3.7,-0.2),weight='bold',color='k',
arrowprops=dict(arrowstyle='-|>',connectionstyle='arc3',color='red'),
bbox=dict(boxstyle='round,pad=0.5',fc='yellow', ec='k',lw=1 ,alpha=0.8))
ax2.set_ylim(-1.5,1.5)
ax2.set_xlim(0,10)
bbox=dict(boxstyle='round',ec='red',fc='white')
ax2.text(6,-1.9,'$y=sin(x)$',bbox=dict(boxstyle='square',facecolor='white',ec='black'))
ax2.grid(ls=":",color='gray',alpha=0.5)
ax2.text(4.5,1,'Povchar',fontsize=15,alpha=0.3,color='gray',bbox=dict(fc="white",boxstyle='round',edgecolor='gray',alpha=0.3))
plt.show()
运行结果:
声明:文章仅供学习使用。著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。