import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider
from matplotlib.patches import Rectangle
# 创建图形和坐标轴
fig, ax = plt.subplots(figsize=(12, 8))
plt.subplots_adjust(bottom=0.2)
# 设置坐标轴范围
ax.set_xlim(-2*np.pi, 2*np.pi)
ax.set_ylim(-1.5, 1.5)
# 绘制x轴和y轴
ax.axhline(y=0, color='k', linestyle='-', linewidth=0.5)
ax.axvline(x=0, color='k', linestyle='-', linewidth=0.5)
# 生成x值和对应的y值(完整的两个周期)
x_full = np.linspace(-2*np.pi, 2*np.pi, 1000)
y_full = np.sin(x_full)
# 绘制完整的正弦函数曲线
ax.plot(x_full, y_full, 'b-', label='f(x) = sin x', alpha=0.5)
# 突出显示 [-π/2, π/2] 区间
x_highlight = np.linspace(-np.pi/2, np.pi/2, 500)
y_highlight = np.sin(x_highlight)
ax.plot(x_highlight, y_highlight, 'b-', linewidth=2)
# 添加区间背景高亮
rect = Rectangle((-np.pi/2, -1), np.pi, 2, facecolor='yellow', alpha=0.2)
ax.add_patch(rect)
# 标注定义域和值域
ax.text(0, -1.3, 'D_f = [-π/2, π/2]', fontsize=12, ha='center')
ax.text(0, -1.1, 'R_f = [-1, 1]', fontsize=12, ha='center')
# 绘制定义域范围
ax.axvline(x=-np.pi/2, color='r', linestyle='--', linewidth=1)
ax.axvline(x=np.pi/2, color='r', linestyle='--', linewidth=1)
# 绘制值域范围
ax.axhline(y=-1, color='g', linestyle='--', linewidth=1)
ax.axhline(y=1, color='g', linestyle='--', linewidth=1)
# 初始x值
init_x = 0
# 创建滑块
ax_slider = plt.axes([0.2, 0.02, 0.6, 0.03])
x_slider = Slider(ax_slider, 'x', -np.pi/2, np.pi/2, valinit=init_x)
# 绘制初始点
point, = ax.plot(init_x, np.sin(init_x), 'ro')
# 更新函数
def update(val):
x = x_slider.val
y = np.sin(x)
point.set_data(x, y)
fig.canvas.draw_idle()
# 连接滑块事件
x_slider.on_changed(update)
# 添加图例
ax.legend()
# 设置标签
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_title('f(x) = sin x 的图像,突出显示 [-π/2, π/2] 区间')
# 设置刻度
ax.set_xticks(np.arange(-2*np.pi, 2*np.pi+np.pi/2, np.pi/2))
ax.set_xticklabels(['-2π', '-3π/2', '-π', '-π/2', '0', 'π/2', 'π', '3π/2', '2π'])
ax.set_yticks([-1, -0.5, 0, 0.5, 1])
plt.grid(True, linestyle=':', alpha=0.6)
plt.show()