import numpy as np import matplotlib.pyplot as plt # 1. 准备数据 x = np.linspace(-np.pi, np.pi, 256, endpoint=True) y_cos = np.cos(x) y_sin = np.sin(x) # 2. 绘制正弦曲线和余弦曲线,设置样式 plt.plot(x, y_sin, color='red', linewidth=1.0, label='Sine') plt.plot(x, y_cos, color='blue', linewidth=1.0, alpha=0.5, label='Cosine') # 3. 设置 x 轴刻度标签 plt.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi], labels=['$-\pi$', '$-\pi/2$', '0', '$\pi/2$', '$\pi$']) # 4. 添加指向型注释文本 x_annotation = 1 y_annotation = np.cos(1) plt.annotate(f'({x_annotation}, {y_annotation:.2f})', xy=(x_annotation, y_annotation), xytext=(x_annotation, y_annotation + 0.5), arrowprops=dict(arrowstyle='->'), fontsize=10) # 5. 填充正弦曲线和余弦曲线之间的区域 plt.fill_between(x, y_sin, y_cos, where=(y_sin > y_cos), color='green', alpha=0.25) # 6. 添加标题和图例 plt.title('Sine and Cosine Curves') plt.legend(loc='upper right') # 7. 显示图表 plt.grid(True) plt.show()
运行结果