从具有多个数据集的散点图中获取 x,y?

2023-12-20

我有一个由不同调用组成的散点图scatter:

import matplotlib.pyplot as plt
import numpy as np

def onpick3(event):
    index = event.ind
    print '--------------'
    print index
    artist = event.artist
    print artist

fig_handle = plt.figure()

x,y = np.random.rand(10),np.random.rand(10)
x1,y1 = np.random.rand(10),np.random.rand(10)

axes_size = 0.1,0.1,0.9,0.9
ax = fig_handle.add_axes(axes_size)

p = ax.scatter (x,y, marker='*', s=60, color='r', picker=True, lw=2)
p1 = ax.scatter (x1,y1, marker='*', s=60, color='b', picker=True, lw=2)

fig_handle.canvas.mpl_connect('pick_event', onpick3)
plt.show()

我希望这些点是可点击的,并获取所选索引的 x,y。 然而自从scatter被多次调用,我得到相同的索引两次,所以我不能使用x[index]在 - 的里面onpick3 method

有没有直接获取积分的方法?

看起来event.artist回馈相同的PathCollection这是从返回的scatter (p and p1在这种情况下)。 但我找不到任何方法来使用它来提取x,y所选索引的 尝试使用event.artist.get_paths()- 但它似乎并没有返回所有的分散点,而是只返回我点击的那个分散点..所以我真的不确定是什么event.artist正在回馈,什么是回馈event.artist.get_paths()功能是回馈

EDIT

看起来event.artist._offsets给出一个具有相关偏移量的数组,但由于某种原因尝试使用时event.artist.offsetsI get

AttributeError: 'PathCollection' object has no attribute 'offsets'

(虽然如果我理解docs http://matplotlib.org/api/collections_api.html?highlight=pathcollection#matplotlib.collections.PathCollection,它应该在那里)


获取集合的 x, y 坐标scatter返回,使用event.artist.get_offsets()(出于历史原因,Matplotlib 有显式的 getter 和 setter。所有get_offsets确实是返回self._offsets,但公共接口是通过“getter”实现的。)。

因此,要完成您的示例:

import matplotlib.pyplot as plt
import numpy as np

def onpick3(event):
    index = event.ind
    xy = event.artist.get_offsets()
    print '--------------'
    print xy[index]


fig, ax = plt.subplots()

x, y = np.random.random((2, 10))
x1, y1 = np.random.random((2, 10))

p = ax.scatter(x, y, marker='*', s=60, color='r', picker=True)
p1 = ax.scatter(x1, y1, marker='*', s=60, color='b', picker=True)

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

但是,如果您不通过第三个或第四个变量来改变事物,您可能不想使用scatter绘制点。使用plot反而。scatter返回一个比使用更难使用的集合Line2D that plot返回。 (如果你确实走使用路线plot,你会用x, y = artist.get_data().)

最后,不要过多地插入我自己的项目,但如果你可能会发现mpldatacursor https://github.com/joferkington/mpldatacursor有用。它抽象了你在这里所做的很多事情。

如果您决定走这条路,您的代码将类似于:

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

从具有多个数据集的散点图中获取 x,y? 的相关文章

随机推荐