nop*_*e11 4 python plot matplotlib
我有一个散点图,由不同的散点图组成:
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()
Run Code Online (Sandbox Code Playgroud)
我希望这些点是可单击的,并获取所选索引的x,y。但是,由于scatter被多次调用,因此两次获得相同的索引,因此无法x[index]在onpick3方法内部使用
是否有一种简单的方法来获得积分?
似乎event.artist还给同样PathCollection是从还给scatter(p和p1在这种情况下)。但是我找不到任何方法来提取x,y尝试使用的选定索引的event.artist.get_paths()-但它似乎并没有放弃所有分散点,而只归还了我单击的那个分散点。所以我真的不确定是什么event.artist回馈了,event.artist.get_paths()功能是回馈了什么
似乎event.artist._offsets给出了具有相关偏移量的数组,但是由于某些原因,当尝试使用时event.artist.offsets我得到
AttributeError: 'PathCollection' object has no attribute 'offsets'
Run Code Online (Sandbox Code Playgroud)
(尽管如果我了解文档,它应该在那里)
要获取scatter返回的集合的x,y坐标,请使用event.artist.get_offsets()(Matplotlib出于大多数历史原因具有显式的getter和setter。所有get_offsets操作都是return 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()
Run Code Online (Sandbox Code Playgroud)
但是,如果您不按第3或第4个变量来改变事物,则可能不希望scatter用于绘制点。使用plot代替。scatter返回集合这是更难的工作比的Line2D是plot回报。(如果您确实使用plot,请使用x, y = artist.get_data()。)
最后,不要过多地插入我自己的项目,但是如果您发现mpldatacursor有用的话。它使您在这里所做的很多事情抽象化。
如果您决定走这条路,您的代码将类似于:
| 归档时间: |
|
| 查看次数: |
2884 次 |
| 最近记录: |