python - matplotlib gui imshow 坐标

标签 python matplotlib pyqt4 imshow

我正在使用 pyqt4 制作一个 GUI,其中包含由 matplotlib 的 imshow 使用二维数组显示的图像。如果我用 pyplot 显示此内容,则当我将鼠标移到图像上时,窗口将显示光标的 x、y 坐标。然而,当我将 imshow 嵌入 pyqt GUI 中时,这似乎消失了。有没有办法让我获得鼠标事件来调用某个函数,该函数返回鼠标悬停点的 x、y 坐标(或者更好的是该二维数组的索引)?

编辑:我找到了 wx 的文档,但我仍然不知道如何为我的 GUI 执行此操作。 wxcursor_demo

如果有帮助,这就是我嵌入 imshow 情节的方法。首先,我创建一个基本 Canvas 类,然后从中为 imshow 创建一个类:

class Canvas(FigureCanvas):
    def __init__(self, parent = None, width = 5, height = 5, dpi = 100, projection = None):
        self.fig = Figure(figsize = (width, height), dpi = dpi)
        if projection:
            self.axes = Axes3D(self.fig)
        else:
            self.axes = self.fig.add_subplot(111)

        self.axes.tick_params(axis = 'both', which = 'major', labelsize = 8)
        self.axes.tick_params(axis = 'both', which = 'minor', labelsize = 8)
        self.compute_initial_figure()
        FigureCanvas.__init__(self, self.fig)
        self.setParent(parent)
        FigureCanvas.setSizePolicy(self, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)
        FigureCanvas.updateGeometry(self)

    def compute_initial_figure(self):
        pass

class TopView(Canvas):
    def __init__(self, *args, **kwargs):
        Canvas.__init__(self, *args, **kwargs)
        self.divider = make_axes_locatable(self.axes)
        self.cax = self.divider.append_axes("bottom", size = "5%", pad = 0.2)

    def compute_initial_figure(self):
        self.top = self.axes.imshow(zarr, interpolation = 'none', extent = [xmin, xmax, ymin, ymax], origin = 'lower')
        self.top.set_cmap('nipy_spectral')
        self.top.set_clim(vmin = pltMin, vmax = pltMax)

然后,在主窗口中,我创建该对象并将其放置在网格布局中:

tv = TopView(self.main_widget, width = 4, height = 3, dpi = 100)
self.g.addWidget(tv, 1, 2, 3, 1)

最佳答案

Matplotlib 使用自己的事件,因此它们独立于 UI 工具包(wx-windows、Qt 等)。因此wxcursor_demo很容易适应 Qt,就像你的情况一样。

首先将以下行添加到 Canvas 类的构造函数

self.mpl_connect('motion_notify_event', self.mouse_moved)

每次鼠标移动时,都会调用 mouse_moved 方法。

mouse_moved 方法中,您可以发出一个连接到知道如何显示鼠标坐标的小部件的 Qt 信号。像这样的事情:

def mouse_moved(self, mouse_event):
    if mouse_event.inaxes:
        x, y = mouse_event.xdata, mouse_event.ydata
        self.mouse_moved_signal.emit(x,y)

当然,您还必须在 Canvas 构造函数中定义 mouse_moved_signal。请注意,mouse_event 参数是 Matplotlib event ,不是 Qt 事件。

我建议您阅读chapter about events在 Matplotlib 文档中了解什么是可能的。

关于python - matplotlib gui imshow 坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30237175/

相关文章:

python - Pandas 根据其他列的条件进行分组求和

python - 如何使用外部 .py 文件?

python - 如何使用 andrew_curves 绘制 Pandas 数据框?

python - 在 matplotlib 中放大插图而不重新绘制数据

python - 如何在 PyQt4 中创建多页应用程序?

python - PyQt4 和 Python 3 - 显示来自 URL 的图像

python - pandas.set_option 提供数据帧的详细信息而不是返回帧

python - 在 Python 中使用 Matplotlib.image 时出错

python - 使用 PyQt4,如何将 mouseMoveEvent 设置为仅在 QMainWindow 中的 QWidget 内部工作,但不在 MainWindow 中工作

python - 如何获取 python 命令行参数(如果它只是一个字符串)