import numpy as np
import matplotlib.pyplot as plt
x=np.linspace(-np.pi,np.pi,256,endpoint=True) #设置x轴区间,256个值
c,s=np.cos(x),np.sin(x) #设置Y轴
plt.figure(1,figsize=(10,6),facecolor="black") #figure用户交互的窗口
plt.plot(x,c,color="blue",linewidth=1.0,linestyle="-",label="cos",alpha=0.7)
plt.plot(x,c,color="green",linewidth=1.0,linestyle=":",label="cos",alpha=0.7)
plt.title("COS&SIN",fontsize=16)
ax=plt.gca() #gca()获取当前的axes绘图区域
ax.spines["right"].set_color("none") #舍弃顶部和右部轴线
ax.spines["top"].set_color("none")
ax.spines["left"].set_position(("data",0)) #将左部和底部的轴线移到数据空间坐标中的零点
ax.spines["bottom"].set_position(("data",0))
ax.xaxis.set_ticks_position("bottom")
ax.yaxis.set_ticks_position("left")
#设置x刻度的值,并将其显示为pi
plt.xticks([-np.pi,-np.pi/2,0,np.pi/2,np.pi],[r'$-\pi$',r'$-\pi/2$',r'$0$',r'$+\pi/2$',r'$+\pi$'])
plt.yticks(np.linspace(-1,1,5,endpoint=True))
for label in ax.get_xticklabels()+ax.get_yticklabels():#设置刻度值的格式,利用for循环
label.set_fontsize(10)
label.set_bbox(dict(facecolor="none",edgecolor="white",alpha=0.5))
plt.legend(loc="upper left") #设置图例位置
plt.fill_between(x,np.abs(x)<0.5,c,c>0.5,color="g",alpha=0.3)
t=1
plt.plot([t,t],[0,np.cos(t)],"red",linewidth=0.8,linestyle="--") #辅助图
#设置注释
plt.annotate("cos(1)",xy=(t,np.cos(1)),xycoords="data",xytext=(+10,+20),textcoords="offset points",arrowprops=dict(arrowstyle="->",connectionstyle="arc3,rad=.2"))
plt.show()
Matplotlib学习
最新推荐文章于 2023-11-23 22:45:10 发布