You need to enable JavaScript to run this app. matplotlib绘制不同振幅余弦曲线时标注极值与零点的报错解决方案
优惠活动
大模型
产品
解决方案
定价
更多

matplotlib绘制不同振幅余弦曲线时标注极值与零点的报错解决方案

代码报错修正与全量标注实现方案

已定位的核心笔误/逻辑问题

  • 函数参数不匹配:h()函数定义时形参写为大写X,但函数内部计算时引用全局小写变量x,存在变量作用域隐患
  • 语法漏写括号:最后调用annot_max(x, g(x))的语句缺失闭合右括号,直接触发Python语法解析报错
  • 标注尺度完全失配:原自定义标注函数设置的文本偏移为xmax+.5, ymax+5,但当前x轴取值范围仅为0~0.05,加0.5的x偏移会把标注文本甩出可视区域,这也是即使改用基础annotate接口也看不到标注的核心原因

可直接运行的完整实现代码

import numpy as np 
import matplotlib.pyplot as plt

# 修正函数参数的作用域不匹配问题
def h(x):
    return 10 * np.cos(120 * np.pi * x + np.pi/6)

def g(x):
    return 5 * np.cos(120 * np.pi * x - np.pi/6)

# 生成连续采样的时间序列
x = np.linspace(0, 0.05, 1000)
y_h = h(x)
y_g = g(x)

# 初始化画布
fig, ax = plt.subplots(figsize=(10,6))
ax.set_ylabel("Voltaje (V)")
ax.set_xlabel("Tiempo (s)")
ax.grid(True, alpha=0.3)

# 通用标注函数:支持极值、零点的统一标注
def point_annotate(x_arr, y_arr, point_type, color, ax):
    """
    point_type可选值: 'max' / 'min' / 'zero'
    """
    if point_type == "max":
        idx = np.argmax(y_arr)
        px, py = x_arr[idx], y_arr[idx]
        label = f"Máx: y={py:.2f}V"
        y_offset = 1.2
        bbox_props = dict(boxstyle="round,pad=0.3", fc="white", ec=color, lw=0.8, alpha=0.9)
        arrowprops = dict(arrowstyle="->", color=color, connectionstyle="arc3,rad=0.2")
        ax.annotate(
            label,
            xy=(px, py),
            xytext=(px + 0.002, py + y_offset),
            xycoords="data",
            textcoords="data",
            arrowprops=arrowprops,
            bbox=bbox_props,
            color=color,
            fontsize=9
        )
    elif point_type == "min":
        idx = np.argmin(y_arr)
        px, py = x_arr[idx], y_arr[idx]
        label = f"Mín: y={py:.2f}V"
        y_offset = -1.8
        bbox_props = dict(boxstyle="round,pad=0.3", fc="white", ec=color, lw=0.8, alpha=0.9)
        arrowprops = dict(arrowstyle="->", color=color, connectionstyle="arc3,rad=0.2")
        ax.annotate(
            label,
            xy=(px, py),
            xytext=(px + 0.002, py + y_offset),
            xycoords="data",
            textcoords="data",
            arrowprops=arrowprops,
            bbox=bbox_props,
            color=color,
            fontsize=9
        )
    elif point_type == "zero":
        # 识别过零点(相邻采样点线性插值计算精确位置)
        zero_idx = np.where(np.diff(np.sign(y_arr)))[0]
        for idx in zero_idx:
            x0, x1 = x_arr[idx], x_arr[idx+1]
            y0, y1 = y_arr[idx], y_arr[idx+1]
            px = x0 - y0*(x1-x0)/(y1-y0)
            py = 0
            # 交替上下偏移避免零点标注全挤在横轴上
            y_offset = 0.7 if idx%2 ==0 else -0.7
            label = f"Cero: t={px:.4f}s"
            bbox_props = dict(boxstyle="round,pad=0.2", fc="white", ec=color, lw=0.7, alpha=0.9)
            arrowprops = dict(arrowstyle="->", color=color, connectionstyle="arc3,rad=0.1")
            ax.annotate(
                label,
                xy=(px, py),
                xytext=(px + 0.001, py + y_offset),
                xycoords="data",
                textcoords="data",
                arrowprops=arrowprops,
                bbox=bbox_props,
                color=color,
                fontsize=8
            )

# 绘制两条曲线,固定线条颜色
line1, = ax.plot(x, y_h, color="#1f77b4", label="grafica 1", linewidth=1.5)
line2, = ax.plot(x, y_g, color="#ff7f0e", label="grafica 2", linewidth=1.5)

# 批量添加所有需要的标注
# 曲线1的极值、零点标注
point_annotate(x, y_h, "max", line1.get_color(), ax)
point_annotate(x, y_h, "min", line1.get_color(), ax)
point_annotate(x, y_h, "zero", line1.get_color(), ax)
# 曲线2的极值、零点标注
point_annotate(x, y_g, "max", line2.get_color(), ax)
point_annotate(x, y_g, "min", line2.get_color(), ax)
point_annotate(x, y_g, "zero", line2.get_color(), ax)

ax.legend(loc=1)
plt.tight_layout()
plt.show()

实现效果说明

  • 所有标注采用和对应曲线一致的配色,不会出现多组标注混淆的问题
  • 标注偏移量适配当前x、y轴的数值范围,不会出现文字甩出画布的问题
  • 零点检测通过相邻采样点的线性插值计算精确位置,不会因采样步长误差导致标注偏移
  • 标注框采用半透明白色背景,可自动覆盖底层网格、曲线,保证文字可读性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.26 15:54:07