利用anaconda3画正余弦图现象,并且给图像进行部分填充、加入注释达到如下图的效果
#导入相应的包
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams['font.family']=['SimHei']
plt.rcParams['axes.unicode_minus']=False
#确定画布大小
fig=plt.figure(figsize=(5,4),dpi=90)
ax=fig.add_subplot()
#确定x轴范围
x=np.linspace(-np.pi,np.pi,256,endpoint=True)
#x,y标签
#plt.xlabel('x')
#plt.ylabel('y')
#x,y的刻度与取值
plt.xticks([-np.pi,-np.pi/2,0,np.pi/2,np.pi],[r"$-\pi$",r"$-\pi/2$","0",r"$\pi/2$",r"$\pi$"])
plt.yticks([-1,0,1])
#移动坐标轴到中间位置
ax.spines['left'].set_position('center')
ax.spines['bottom'].set_position('center')
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
#函数
plt.plot(x,np.sin(x))
plt.plot(x,np.cos(x))
#绘图填充
#方法一:根据条件打印出的True的区间来确定
#print((-2.5<x)&(x<-0.5))
plt.fill_between(x[28:108],np.cos(x)[28:108],facecolor='purple',alpha=1)
#print((np.sin(x)>0.5))
plt.fill_between(x[150:234],np.sin(x)[150:234],facecolor='green',alpha=1)
#方法二:
#a=x[(-2.5<x)&(x<-0.5)]
#plt.fill_between(a,np.cos(a),facecolor='purple',alpha=1)
#plt.fill_between(x,np.sin(x),where=(np.sin(x)>0.5),facecolor='green',alpha=1)
#方法三:
#a=x[(-2.5<x)&(x<-0.5)]
#plt.fill_between(a,np.cos(a),facecolor='purple',alpha=1)
#b=x[(x>0.5)&(x<np.pi-0.5)]
#plt.fill_between(b,np.sin(b),facecolor='green',alpha=1)
#给图加入文本注释案例
bbox=dict(boxstyle='round',fc='white')
ax.annotate(r'$ \sin(\frac{3\pi}{2})=\frac{\sqrt{3}}{2} $',xy=(2*np.pi/3,np.sin(2*np.pi/3)),xytext=(3,np.sqrt(3)/2),\
arrowprops=dict(facecolor='black',edgecolor='red',headwidth=5,width=3))
plt.grid()
#图例
plt.legend(['正弦sin()','余弦cos()'])
plt.show()