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

如何移除Matplotlib中滑块更新添加的最后一个标记?

解决Matplotlib滑块切换时移除旧选中标记的问题

你的代码目前每次拖动滑块都会添加新的红桃标记,但旧标记不会被移除,导致标记越积越多。核心解决思路是保存当前选中标记的对象引用,每次更新时先移除旧标记,再添加新标记。

修改后的完整代码如下:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider, Button, RadioButtons

fig, ax = plt.subplots()
plt.subplots_adjust(left=0.25, bottom=0.25)
f0 = 0
val = 0

# Sample Data
pos_x = [0.0, 1.0, 2.5, 4.0, 8.8]
pos_y = [1.3, 2.0, 6.5, 5.0, 7.0]

# Plot all data
ax.plot(pos_x, pos_y, color="blue", marker=r'$\diamond$', linestyle='-', label="Robo")

axfreq = plt.axes([0.25, 0.1, 0.65, 0.03], facecolor="blue")

# Create slider that will move current selection
sfreq = Slider(axfreq, 'Freq', valmin=0.0, valmax=4.0, valinit=f0, valstep=1, dragging=True)

# 保存初始选中标记的对象引用
selected_marker = ax.scatter(pos_x[int(val)], pos_y[int(val)], color="red", marker=r'$\spadesuit$', s=100)

# Function to update location and remove last marker
def update(val):
    global selected_marker
    # 移除上一个选中的标记
    selected_marker.remove()
    # 添加新的选中标记,并更新引用
    selected_marker = ax.scatter(pos_x[int(val)], pos_y[int(val)], color="red", marker=r'$\spadesuit$', s=100)
    print(pos_x[int(val)], pos_y[int(val)])
    fig.canvas.draw_idle()

sfreq.on_changed(update)

ax.legend()
plt.show()

关键修改点说明:

  • 初始化时将ax.scatter()的返回值赋值给selected_marker,这个返回值是Matplotlib的PathCollection对象,代表当前的红桃标记。
  • 在update函数中,先调用selected_marker.remove()将旧标记从轴上移除,然后重新创建新标记并覆盖selected_marker的引用,确保每次滑块切换后只有当前选中的标记存在。
  • 使用global selected_marker确保函数内部可以修改全局变量的引用。

这样就能实现拖动滑块时,旧的选中标记被移除,只显示当前选中的数据点标记。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 02:25:39