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

如何在Plotly Dash中实现可拖拽动态文本注释的增删?

实现Python图表动态文本注释(添加/删除/拖拽)

以matplotlib为例,通过事件监听系统实现动态注释功能,以下是完整实现方案:

核心逻辑

利用matplotlib的mpl_connect绑定鼠标、键盘事件,维护注释对象列表,实现添加、拖拽、删除操作。

1. 初始化环境

先创建绘图基础环境,定义管理注释的变量:

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.plot([1,2,3,4], [1,4,9,16])  # 替换为你的业务数据

# 注释管理变量
annotations = []
current_dragging = None
drag_start_pos = None

2. 实现添加注释功能

右键点击图表区域触发,弹出输入框获取文本后创建注释:

def on_mouse_press(event):
    global current_dragging, drag_start_pos
    # 右键添加注释
    if event.button == 3 and event.inaxes == ax:
        text = input("输入注释文本:")
        if text:
            annot = ax.annotate(
                text,
                xy=(event.xdata, event.ydata),
                xytext=(event.xdata+0.1, event.ydata+0.1),
                bbox=dict(facecolor='yellow', alpha=0.5),
                arrowprops=dict(arrowstyle="->")
            )
            annotations.append(annot)
            fig.canvas.draw_idle()
    # 左键选中注释准备拖拽
    elif event.button == 1 and event.inaxes == ax:
        for annot in annotations:
            if annot.contains(event)[0]:
                current_dragging = annot
                drag_start_pos = (event.xdata, event.ydata)
                break

3. 实现拖拽调整位置

鼠标移动时实时更新选中注释的位置:

def on_mouse_move(event):
    global current_dragging, drag_start_pos
    if current_dragging is not None and event.inaxes == ax:
        dx = event.xdata - drag_start_pos[0]
        dy = event.ydata - drag_start_pos[1]
        # 更新注释文本位置
        pos = current_dragging.get_position()
        current_dragging.set_position((pos.x + dx, pos.y + dy))
        # 更新箭头指向的锚点
        current_dragging.xy = (current_dragging.xy[0] + dx, current_dragging.xy[1] + dy)
        drag_start_pos = (event.xdata, event.ydata)
        fig.canvas.draw_idle()

4. 实现删除注释功能

选中注释后按Delete或D键删除:

def on_key_press(event):
    global current_dragging
    if event.key in ['delete', 'd'] and current_dragging is not None:
        current_dragging.remove()
        annotations.remove(current_dragging)
        current_dragging = None
        fig.canvas.draw_idle()

5. 绑定事件并启动交互

将事件绑定到画布,启动绘图交互:

# 绑定各类事件
fig.canvas.mpl_connect('button_press_event', on_mouse_press)
fig.canvas.mpl_connect('motion_notify_event', on_mouse_move)
fig.canvas.mpl_connect('button_release_event', lambda e: globals().update(current_dragging=None))
fig.canvas.mpl_connect('key_press_event', on_key_press)

plt.show()

使用说明

  • 右键点击图表任意位置,输入文本后回车即可添加注释
  • 左键点击注释可选中,拖动鼠标即可调整注释位置
  • 选中注释后按Delete或D键,即可删除该注释

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 11:03:35