gpt4 book ai didi

python - Matplotlib 从多个系列中选择事件

转载 作者:行者123 更新时间:2023-11-30 22:32:01 25 4
gpt4 key购买 nike

我正在制作一个散点图,我想单击各个点来执行某些操作。这就像现有的示例代码。

https://matplotlib.org/examples/event_handling/pick_event_demo.html

我已经实现了 on_pick 方法

def on_pick(event):
ind = event.ind
for i in ind:
...do something here with blue or red data...

但是,我陷入困境,因为我将多个系列(红色和蓝色)放在同一个图中

fig, ax = plt.subplots()
ax.set_title('click on a point...')
line, = ax.plot(red_xs, red_ys, 'o', picker=5, color='red')
line, = ax.plot(blue_xs, blue_ys, 'o', picker=5, color='blue')

event.ind 是整数的集合。它们是系列的索引。但是,似乎无法确定它们是哪个系列的索引。

一定有办法做到这一点。有谁知道其中的窍门吗?

谢谢彼得

最佳答案

这是我找到的解决方案。它看起来很笨重,但也许这是最好的。

通过编写“自定义选择器”,可以将元数据添加到事件中。这里我添加“ind”和“series”

def picker(self,line,mouseevent,series):
if mouseevent.xdata is None:
return False, dict()
xdata = line.get_xdata()
ydata = line.get_ydata()
maxd = 0.05
d = np.sqrt((xdata - mouseevent.xdata) ** 2. + (ydata - mouseevent.ydata) ** 2.)

ind = np.nonzero(np.less_equal(d, maxd))
if len(ind):
props = dict(ind=ind, series=series)
return True, props
else:
return False, dict()

然后可以将不同的“自定义选择器”附加到每个散点图

    line, = ax.plot(self.red['False'], self.red['True'], 'o', picker=lambda line,mouseevent: self.picker(line,mouseevent,self.red), color='red')
line, = ax.plot(self.blue['False'], self.blue['True'], 'o', picker=lambda line,mouseevent: self.picker(line,mouseevent,self.blue), color='blue')

然后在 on_pick() 函数中提取元数据

fig.canvas.mpl_connect('pick_event', lambda e: self.on_pick(e))

...

def on_pick(self,event):
for i in event.ind:
for j in i:
series = event.series
...do something with item j of series...

关于python - Matplotlib 从多个系列中选择事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45621544/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com