【问题标题】:matplotlib onclick event repeatingmatplotlib onclick 事件重复
【发布时间】:2016-03-13 20:00:57
【问题描述】:

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

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()

【问题讨论】:

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


    【解决方案1】:

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

    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()
    

    【讨论】:

    • 这很有帮助,但我还是不明白如何从函数调用中取回 x 和 y 坐标?我想存储点击坐标并在其他功能中使用它们。我知道,我可以在同一个函数中使用它们。
    • @xtlc xcoordsycoords 是全局变量,因此所有其他函数都应该可以访问它们
    • 对不起,我解释得不好:当我点击时,我可以使用函数中的坐标,但是在函数之外发生的一切都停止了。例如,如果我想在def onclick(event) 之外打印坐标怎么办?这就是为什么我想要“像一个循环”的东西。
    猜你喜欢
    • 2023-03-07
    • 1970-01-01
    • 2021-06-22
    • 2016-05-09
    • 1970-01-01
    • 2021-07-22
    • 2015-05-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多