我想在曲线上拾取(添加)标记。标记可能会多次更改位置,但是最终我只需要绘制最新(更新)的标记并删除旧标记。 有什么想法吗?
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()
答案 0 :(得分:0)
与其在每次点击时都调用新的plot()
并创建一个新的美术师,不如在初始化阶段创建一个空的美术师,并在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()
编辑:使用N条曲线和N条标记的相同原理
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()