matplotlib onclick事件重复

时间:2016-03-13 20:00:58

标签: python python-3.x matplotlib event-handling mouseevent

我想使用onclick方法在matplotlib图上选择一系列数据。但问题是,我不能不止这样做并更新情节。我有一些想法可以做到这一点,其中一个是制作一个图表列表,在我添加新图片后跳转到新索引...但大多数情况下我希望能够存储点击信息( event.xdata)两次为该部分中的图形下方的区域着色 - 但对于初学者来说,无论我在哪里点击都会成为一个成就。但我认为有一个更好的解决方案,而不是在plt.draw()函数中放置onclick

import numpy as np
import matplotlib.pyplot as plt
from itertools import islice

class ReadFile():
    def __init__(self, filename):
        self._filename = filename

    def read_switching(self):
        return np.genfromtxt(self._filename, unpack=True, usecols={0}, delimiter=',')

def onclick(event):
    global ix, iy
    ix, iy = event.xdata, event.ydata
    global coords
    coords.append((ix, iy))
    print(coords)
    fig.canvas.mpl_disconnect(cid)
    return coords

coords = []    
filename = 'test.csv'
fig = plt.figure()
ax = fig.add_subplot(111)
values = (ReadFile(filename).read_switching())
steps = np.arange(1, len(values)+1)*2
graph_1, = ax.plot(steps, values, label='original curve')
cid = fig.canvas.mpl_connect('button_press_event', onclick)
print(coords)
graph_2, = ax.plot(coords, marker='o')
plt.show()

例如,我有以下功能(图片),我想点击两个坐标并为图表下的区域着色,可能是plt.draw()Example function

1 个答案:

答案 0 :(得分:1)

问题是您正在断开回调中的on_click事件。相反,您需要更新xdata对象的ydatagraph_2。然后强制重绘图形

import numpy as np
import matplotlib.pyplot as plt


fig = plt.figure()
ax = fig.add_subplot(111)

# Plot some random data
values = np.random.rand(4,1);
graph_1, = ax.plot(values, label='original curve')
graph_2, = ax.plot([], marker='o')

# Keep track of x/y coordinates
xcoords = []
ycoords = []

def onclick(event):
    xcoords.append(event.xdata)
    ycoords.append(event.ydata)

    # Update plotted coordinates
    graph_2.set_xdata(xcoords)
    graph_2.set_ydata(ycoords)

    # Refresh the plot
    fig.canvas.draw()

cid = fig.canvas.mpl_connect('button_press_event', onclick)
plt.show()