Matplotlib数据二维绘图实践

tech2025-01-19  2

通过 Matplotlib 绘制出下图这副图像

Code

from matplotlib import pyplot as plt import numpy as np #尺寸_figsize,分辨率_dpi plt.figure(figsize=(8, 5), dpi=80) axes = plt.subplot() #顶部和右侧边框设为隐藏 axes.spines['top'].set_color('none') axes.spines['right'].set_color('none') #设置xy轴位置 axes.xaxis.set_ticks_position('bottom') axes.spines['bottom'].set_position(('data', 0)) axes.yaxis.set_ticks_position('left') axes.spines['left'].set_position(('data', 0)) #xy数据 x=np.linspace(-1*np.pi, np.pi, 1000) ys=np.sin(x) yc=np.cos(x) axes.plot(x, ys, color='red', linestyle='-', linewidth=2.5, label='Sin Function') axes.plot(x, yc, color='blue', linestyle='-', linewidth=2.5, label='Cos Function') #限制xy plt.xlim(x.min()*1.1, x.max()*1.1) plt.ylim(ys.min()*1.1, ys.max()*1.1) #标注xy轴 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([-1, 1], [r'$-1$', r'$+1$']) t=np.pi*2/3 ts=np.sin(t) tc=np.cos(t) #标记点 plt.scatter(t, ts, linewidth=1.5, color='red') plt.scatter(t, tc, linewidth=1.5, color='blue') plt.plot(np.ones(100)*t, np.linspace(0, ts, 100), linestyle='--', color='red', linewidth=1.5) plt.plot(np.ones(100)*t, np.linspace(tc, 0, 100), linestyle='--', color='blue', linewidth=1.5) # 增加箭头标注 plt.annotate(r'$\sin{(\frac{2\pi}{3})}=\frac{\sqrt{3}}{2}$',#Latex xy=(t, ts), xytext=(+10, +30), textcoords='offset points', fontsize=16, arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2")) plt.annotate(r'$\cos{(\frac{2\pi}{3})}=-\frac{1}{2}$', xy=(t, tc), xytext=(-90, -50), textcoords='offset points', fontsize=16, arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2")) axes.legend(loc='upper left',frameon=False) plt.show()

前置知识

ax.spines——matplotlib坐标轴设置 matplotlib.pyplot.annotate

最新回复(0)