我有一堆时间序列数据,每5秒就有一个点数。因此,我可以创建一个线图,甚至可以平滑数据以获得更平滑的图。问题是,在matplotlib或python中的任何方法中是否有任何方法可以让我点击有效点来做某事?因此,举例来说,如果我的原始数据中存在该数据,我可以点击(10,75),然后我就能用Python做点什么。
有什么想法?感谢。
答案 0 :(得分:8)
要扩展@tcaswell所说的内容,请参阅此处的文档:http://matplotlib.org/users/event_handling.html
但是,您可能会发现有用的选择事件的快速演示:
import matplotlib.pyplot as plt
def on_pick(event):
artist = event.artist
xmouse, ymouse = event.mouseevent.xdata, event.mouseevent.ydata
x, y = artist.get_xdata(), artist.get_ydata()
ind = event.ind
print 'Artist picked:', event.artist
print '{} vertices picked'.format(len(ind))
print 'Pick between vertices {} and {}'.format(min(ind), max(ind)+1)
print 'x, y of mouse: {:.2f},{:.2f}'.format(xmouse, ymouse)
print 'Data point:', x[ind[0]], y[ind[0]]
print
fig, ax = plt.subplots()
tolerance = 10 # points
ax.plot(range(10), 'ro-', picker=tolerance)
fig.canvas.callbacks.connect('pick_event', on_pick)
plt.show()
您的具体处理方式取决于您使用的是哪位艺术家(换句话说,您使用ax.plot
与ax.scatter
对比ax.imshow
?)。
根据所选的艺术家,挑选事件将具有不同的属性。始终会有event.artist
和event.mouseevent
。大多数具有单独元素的艺术家(例如Line2D
s,Collections
等)将具有选择为event.ind
的项目的索引列表。
如果您想绘制多边形并选择内部点,请参阅:http://matplotlib.org/examples/event_handling/lasso_demo.html#event-handling-example-code-lasso-demo-py
答案 1 :(得分:0)
如果要在艺术家对象上绑定额外的属性(例如,正在绘制几部电影的IMDB等级),并且想要通过单击与电影对应的点来观看,则可以通过添加一个自定义对象,直到绘制出点,像这样:
import matplotlib.pyplot as plt
class custom_objects_to_plot:
def __init__(self, x, y, name):
self.x = x
self.y = y
self.name = name
a = custom_objects_to_plot(10, 20, "a")
b = custom_objects_to_plot(30, 5, "b")
c = custom_objects_to_plot(40, 30, "c")
d = custom_objects_to_plot(120, 10, "d")
def on_pick(event):
print(event.artist.obj.name)
fig, ax = plt.subplots()
for obj in [a, b, c, d]:
artist = ax.plot(obj.x, obj.y, 'ro', picker=5)[0]
artist.obj = obj
fig.canvas.callbacks.connect('pick_event', on_pick)
plt.show()
现在,当您单击绘图上的点之一时,将打印相应对象的name属性。