# /// script # requires-python = ">=3.11" # dependencies = ["numpy", "matplotlib"] # /// import numpy as np import matplotlib.pyplot as plt # 设置字体 plt.rcParams['font.sans-serif'] = ['WenQuanYi Micro Hei', 'Noto Sans CJK SC', 'Microsoft YaHei', 'SimHei', 'SimSun', 'DejaVu Sans'] plt.rcParams['axes.unicode_minus'] = False # 创建图形 fig, ax = plt.subplots(figsize=(10, 8), dpi=150) # 定义函数 def f(x): return -2*x**2 + 8*x - 3 # 生成 x 数据(根据顶点位置设置合理范围) x = np.linspace(-1, 5, 500) y = f(x) # 绘制函数曲线 ax.plot(x, y, 'b-', linewidth=2.5, label=r'$y = -2x^2 + 8x - 3$') # 标记顶点 vertex_x, vertex_y = 2, 5 ax.scatter([vertex_x], [vertex_y], color='red', s=120, zorder=5, edgecolors='darkred', linewidths=2) ax.annotate(f'顶点 ({vertex_x}, {vertex_y})\n最大值', xy=(vertex_x, vertex_y), xytext=(vertex_x + 0.8, vertex_y + 0.5), fontsize=12, ha='left', arrowprops=dict(arrowstyle='->', color='red', lw=1.5), bbox=dict(boxstyle='round,pad=0.3', facecolor='lightyellow', edgecolor='orange')) # 标记与 x 轴的交点(求根) # -2x² + 8x - 3 = 0 → x = (8 ± √(64-24))/(-4) = (8 ± √40)/(-4) discriminant = 64 - 24 x1 = (8 - np.sqrt(discriminant)) / 4 x2 = (8 + np.sqrt(discriminant)) / 4 ax.scatter([x1, x2], [0, 0], color='green', s=100, zorder=5, marker='s', edgecolors='darkgreen', linewidths=2) ax.annotate(f'x ≈ {x1:.2f}', xy=(x1, 0), xytext=(x1 - 0.3, -1.5), fontsize=10, ha='center', arrowprops=dict(arrowstyle='->', color='green', lw=1)) ax.annotate(f'x ≈ {x2:.2f}', xy=(x2, 0), xytext=(x2 + 0.3, -1.5), fontsize=10, ha='center', arrowprops=dict(arrowstyle='->', color='green', lw=1)) # 绘制对称轴 ax.axvline(x=vertex_x, color='purple', linestyle='--', linewidth=1.5, alpha=0.7, label=f'对称轴 x = {vertex_x}') # 绘制参考线 ax.axhline(y=0, color='gray', linestyle='-', linewidth=0.8, alpha=0.5) ax.axhline(y=vertex_y, color='orange', linestyle=':', linewidth=1.5, alpha=0.7, label=f'最大值 y = {vertex_y}') # 填充顶点到 x 轴的区域(可视化最大值) x_fill = np.linspace(x1, x2, 100) y_fill = f(x_fill) ax.fill_between(x_fill, y_fill, 0, alpha=0.15, color='blue', label='函数值 > 0 的区域') # 设置坐标轴 ax.set_xlim(-1, 5) ax.set_ylim(-4, 7) ax.set_xlabel('x', fontsize=14) ax.set_ylabel('y', fontsize=14) ax.set_title(r'二次函数 $y = -2x^2 + 8x - 3$ 图像', fontsize=16, fontweight='bold') # 添加网格 ax.grid(True, linestyle='--', alpha=0.4) # 添加图例 ax.legend(loc='lower right', fontsize=11, framealpha=0.9) # 添加说明文字框 textstr = '\n'.join([ '关键信息:', f'• 顶点坐标: ({vertex_x}, {vertex_y})', f'• 最大值: {vertex_y}', f'• 开口方向: 向下 (a < 0)', f'• 对称轴: x = {vertex_x}' ]) props = dict(boxstyle='round', facecolor='white', edgecolor='gray', alpha=0.9) ax.text(0.02, 0.98, textstr, transform=ax.transAxes, fontsize=11, verticalalignment='top', bbox=props) plt.tight_layout() plt.savefig('figure.png', bbox_inches='tight', facecolor='white') plt.close() print("图像已保存: figure.png")