You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Matplotlib绘制的函数图像上添加指定点?

在函数图像上标记指定点的解决方案

没问题,要在你的二次函数图像上标记f(-2)和f(2)对应的点其实很简单,咱们直接在现有代码基础上补充几行就能实现,甚至还能把点标注得更清晰易懂。

完整实现代码

import numpy as np
import matplotlib.pyplot as plt

def f(x): return x ** 2 + 2 * x + 4

# 生成x取值范围并绘制函数曲线
x_val = np.linspace(-6, 6)
graph = f(x_val)
plt.plot(x_val, graph)

# 定义需要标记的x值,计算对应的y值
target_xs = [-2, 2]
target_ys = [f(x) for x in target_xs]

# 用红色散点标记指定点,设置大小让点更显眼
plt.scatter(target_xs, target_ys, color='red', s=60, label='目标点')

# 给每个点添加坐标标注,方便查看具体数值
for x, y in zip(target_xs, target_ys):
    plt.annotate(f'({x}, {y:.1f})',  # 保留一位小数让标注更整洁
                 (x, y),
                 textcoords="offset points",
                 xytext=(0, 12),  # 让标注在点上方12像素处
                 ha='center',
                 fontsize=10)

# 添加图例、标题和坐标轴标签,提升图像可读性
plt.legend()
plt.title('函数 $f(x) = x^2 + 2x + 4$ 及指定点', fontsize=12)
plt.xlabel('x')
plt.ylabel('f(x)')

plt.show()

关键步骤解释

  • 标记点核心操作:用plt.scatter()绘制离散点,通过color和s(大小)参数让目标点在函数曲线上更突出;
  • 添加坐标标注:plt.annotate()可以给每个点加上具体的坐标值,避免读者自己估算,xytext参数用来调整标注的位置,防止遮挡点本身;
  • 简化版可选:如果不需要标注和图例,只需要一行代码就能完成标记:
    plt.scatter([-2, 2], [f(-2), f(2)], color='red', s=60)
    

这样运行代码后,你就能清晰看到函数曲线上的两个目标点啦!

内容的提问来源于stack exchange,提问作者jee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 15:52:39