简体   繁体   中英

How to draw only one, the newest point selected by pick_event?

I want to pick (add) marker to the curve. The marker may change the position many times, however eventually I need to plot only the newest (updated) marker and remove the old. Any ideas?

import matplotlib.pyplot as plt
import numpy as np

fig, ax1 = plt.subplots()
t = np.arange(0.0, 1.0, 0.01)
s = np.sin(2 * 2 * np.pi * t)for i in range(10):
pt, = ax1.plot(t, s, picker=5)


def onpick(event):

    if event.artist != pt:
        return True
    if not len(event.ind):
        return True
    ind = event.ind[0]
    ax1.plot(t[ind], s[ind], '|r', markersize='20')
    fig.canvas.draw()
    return True


fig.canvas.mpl_connect('pick_event', onpick)
plt.show()

Instead of calling a new plot() and creating a new artist at every click, simply create an empty artist at initialization stage, and update its coordinates in onpick() :

import matplotlib.pyplot as plt
import numpy as np

fig, ax1 = plt.subplots()
t = np.arange(0.0, 1.0, 0.01)
s = np.sin(2 * 2 * np.pi * t)
pt, = ax1.plot(t, s, picker=5)
mark, = ax1.plot([], [], '|r', markersize='20')


def onpick(event):
    if event.artist != pt:
        return True
    if not len(event.ind):
        return True
    ind = event.ind[0]
    mark.set_data(t[ind], s[ind])
    fig.canvas.draw()
    return True


fig.canvas.mpl_connect('pick_event', onpick)
plt.show()

EDIT: same principle using N curves and N markers

import matplotlib.pyplot as plt
import numpy as np

fig, ax1 = plt.subplots()
t = np.arange(0.0, 1.0, 0.01)
ss = [np.sin(2 * 2 * np.pi * t),
      np.cos(3 * 2 * np.pi * t),
      np.sin(0.5 * 2 * np.pi * t)]
cs = ['b','r', 'g']
ms = ['|','o','D']
lines = [ax1.plot(t,s,'-',color=c, picker=5)[0] for s,c in zip(ss,cs)]
markers = [ax1.plot([],[],lw=0, marker=m, ms=20, color=c)[0] for m,c in zip(ms,cs)]

def onpick(event):
    point_idx = event.ind[0]
    art_idx = None
    for i,l in enumerate(lines):
        if event.artist == l:
            art_idx = i
            break
    if art_idx is not None:
        markers[art_idx].set_data(t[point_idx], ss[art_idx][point_idx])
    fig.canvas.draw()
    return True


fig.canvas.mpl_connect('pick_event', onpick)
plt.show()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM