《数据分析与可视化》(清华)ch6-实训1代码 可运行

原答案会报错

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()

运行结果:

声明:文章仅供学习使用。著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值