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

关于在Matplotlib中实现示波器风格双光标差值功能的技术问询

关于在Matplotlib中实现示波器风格双光标差值功能的技术问询

嘿,这个需求我之前折腾过,完全可以实现!示波器那种双光标实时显示X/Y差值的效果,核心就是借助Matplotlib的光标工具+自定义差值计算逻辑,我给你整理了亲测可用的代码和思路:

核心实现思路

示波器风格的双光标,本质是两个可拖动的十字光标,实时计算并显示它们在X轴、Y轴上的差值。我们可以用matplotlib.widgets.Cursor创建两个独立光标,再绑定鼠标移动事件来更新差值标注。

完整代码示例

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.widgets import Cursor

# 生成测试数据(模拟示波器波形)
x = np.linspace(0, 10, 1000)
y = np.sin(x) + 0.5*np.cos(3*x)

# 创建绘图窗口
fig, ax = plt.subplots(figsize=(10, 6))
line, = ax.plot(x, y, color='#1f77b4', linewidth=1.5)
ax.set_xlabel('Time (s)')
ax.set_ylabel('Amplitude')
ax.set_title('Oscilloscope-style Dual Cursor with Delta Values')
ax.grid(True, alpha=0.3)

# 初始化两个光标,用不同颜色区分
cursor1 = Cursor(ax, useblit=True, color='red', linewidth=1)
cursor2 = Cursor(ax, useblit=True, color='blue', linewidth=1)

# 初始化差值标注文本,放在右上角
delta_text = ax.text(0.95, 0.95, '', transform=ax.transAxes,
                     ha='right', va='top', fontsize=12,
                     bbox=dict(facecolor='white', alpha=0.8))

# 定义差值更新函数
def update_delta(event):
    # 确保两个光标都有当前位置
    if cursor1.visible and cursor2.visible:
        x1, y1 = cursor1.x, cursor1.y
        x2, y2 = cursor2.x, cursor2.y
        # 计算差值(保留两位小数)
        delta_x = round(abs(x2 - x1), 2)
        delta_y = round(abs(y2 - y1), 2)
        # 更新标注文本
        delta_text.set_text(f'ΔX: {delta_x}\nΔY: {delta_y}')
        fig.canvas.draw_idle()

# 绑定鼠标移动事件
fig.canvas.mpl_connect('motion_notify_event', update_delta)

plt.tight_layout()
plt.show()

关键细节说明

  • 光标样式:通过Cursor的color和linewidth参数设置示波器风格的十字线,useblit=True能提升拖动时的流畅度
  • 差值计算:在鼠标移动事件回调里,获取两个光标的实时坐标,计算绝对值差值后更新标注
  • 标注位置:用transAxes将文本固定在绘图区域的右上角,不会随坐标轴缩放移动

如果需要更贴近示波器的交互(比如锁定某一光标、切换差值模式),还可以扩展代码添加按钮控件,比如用matplotlib.widgets.Button实现光标锁定功能。

备注:内容来源于stack exchange,提问作者Guillaume G

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.23 07:53:18