matplotlib 如何删除通过滑块更新添加的最后一个标记?

xxhby3vn  于 2023-05-07  发布在  其他
关注(0)|答案(1)|浏览(186)

我希望从图中删除最后一个标记,以显示当前的数据点选择。下面是我的代码:

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)

# Adds marker at first x,y
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):
    freq = sfreq.val
    ax.scatter(pos_x[int(val)], pos_y[int(val)], color="red", marker=r'$\spadesuit$', s=100)
    # remove last marker
    print(pos_x[int(val)], pos_y[int(val)])
    fig.canvas.draw_idle()

sfreq.on_changed(update)

ax.legend()
plt.show()

我现在用的是Python 3.9
我一直在试图找到某种方法来恢复到基本情节,然后重新添加标记到新的位置。

kx7yvsdv

kx7yvsdv1#

update(val)函数中,您不希望创建新的散点图,而是希望更新已创建的散点图。因此,在创建图时保存对图的引用,例如将其命名为my_scatter_point

# Adds marker at first x,y
my_scatter_point = ax.scatter(
    pos_x[int(val)], pos_y[int(val)],
    color="red", marker=r'$\spadesuit$', s=100)

现在,在update函数中,您可以使用my_scatter_point.set_offsets(...)来更新值。你不必重新设置颜色和标记。

def update(val):
    freq = sfreq.val
    my_scatter_point.set_offsets((pos_x[int(val)], pos_y[int(val)]))
    # remove last marker
    print(pos_x[int(val)], pos_y[int(val)])
    fig.canvas.draw_idle()

现在,当您更改滑块时,绘图将更新地物。

相关问题