python - Matplotlib 可拖动数据标记

标签 python matplotlib

我需要一个可拖动的数据标记来手动调整数据集中的一组点。 This answer 和其他人使用 Patch.Circle 解决了这个问题。但是,我需要标记在缩放绘图时保持相同的大小。有了圆圈,圆圈也会缩放。我没有尝试找到一种在每次新缩放时动态调整圆圈大小的方法,因为看起来应该有一种更简单的方法来移动标记。有人知道怎么做吗?

最佳答案

下面,我展示了一个 MWE,它展示了一种使用 matplotlib 和 PyQt4 的面向对象 API 来实现它的方法。可以使用鼠标中键拖动数据标记。该策略是使用 line2D 艺术家绘制您的数据,然后通过操纵艺术家的数据和更新绘图来拖动标记。这可以大致概括为 3 个步骤:

第 1 步 - 单击鼠标中键时,会将鼠标光标的坐标(以像素为单位)与 line2D 艺术家的以像素为单位的 xy 数据进行比较。如果光标与最近标记之间的线性距离小于给定值(此处定义为标记的大小),则该数据标记的索引将保存在类属性 draggable 中。否则,draggable 设置为 None

第2步 - 当鼠标移动时,如果draggable不为None,其索引存储在类属性draggable中的数据标记的坐标 设置为鼠标光标的那些。

第 3 步 - 松开鼠标中键时,draggable 设置回 None。

注意:如果需要,也可以使用 pyplot 接口(interface)而不是面向对象的 API 来生成图形。

import sys
from PyQt4 import QtGui
from matplotlib.figure import Figure
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg
from matplotlib.backends.backend_qt4agg import FigureManagerQT
import numpy as np


class MyFigureCanvas(FigureCanvasQTAgg):
    def __init__(self):
        super(MyFigureCanvas, self).__init__(Figure())
        # init class attributes:
        self.background = None
        self.draggable = None
        self.msize = 6
        # plot some data:
        x = np.random.rand(25)
        self.ax = self.figure.add_subplot(111)
        self.markers, = self.ax.plot(x, marker='o', ms=self.msize)
        # define event connections:
        self.mpl_connect('motion_notify_event', self.on_motion)
        self.mpl_connect('button_press_event', self.on_click)
        self.mpl_connect('button_release_event', self.on_release)

    def on_click(self, event):
        if event.button == 2:  # 2 is for middle mouse button
            # get mouse cursor coordinates in pixels:
            x = event.x
            y = event.y
            # get markers xy coordinate in pixels:
            xydata = self.ax.transData.transform(self.markers.get_xydata())
            xdata, ydata = xydata.T
            # compute the linear distance between the markers and the cursor:
            r = ((xdata - x)**2 + (ydata - y)**2)**0.5
            if np.min(r) < self.msize:
                # save figure background:
                self.markers.set_visible(False)
                self.draw()
                self.background = self.copy_from_bbox(self.ax.bbox)
                self.markers.set_visible(True)
                self.ax.draw_artist(self.markers)
                self.update()
                # store index of draggable marker:
                self.draggable = np.argmin(r)
            else:
                self.draggable = None

    def on_motion(self, event):
        if self.draggable is not None:
            if event.xdata and event.ydata:
                # get markers coordinate in data units:
                xdata, ydata = self.markers.get_data()
                # change the coordinate of the marker that is
                # being dragged to the ones of the mouse cursor:
                xdata[self.draggable] = event.xdata
                ydata[self.draggable] = event.ydata
                # update the data of the artist:
                self.markers.set_xdata(xdata)
                self.markers.set_ydata(ydata)
                # update the plot:
                self.restore_region(self.background)
                self.ax.draw_artist(self.markers)
                self.update()

    def on_release(self, event):
        self.draggable = None

if __name__ == '__main__':

    app = QtGui.QApplication(sys.argv)

    canvas = MyFigureCanvas()
    manager = FigureManagerQT(canvas, 1)
    manager.show()

    sys.exit(app.exec_())

enter image description here

关于python - Matplotlib 可拖动数据标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40267961/

相关文章:

python - 知道将 Python 与 Tcl 接口(interface)的任何创造性方法吗?

python - 为 csv 中的列创建不同的元组值并计算第三列的平均值

python - 拟合 Von Mises 分布的圆形直方图

python - Matplotlib 找不到 Facefile,正在使用旧的 Python 解释器位置

python - 检查点是否在python中的多边形内的最快方法是什么

python - 使用 pandas 绘制相关矩阵

python - 使用selenium webdriver python通过xpath登录jsp表单

python - 带有 Pandas 的 REGEX 过滤器(任何数字组合后跟 'plus' 符号)

python - 使用Python中不同大小网格点的数据生成3D曲面图

python - 有没有办法让一个循环在后台运行,而其他代码继续在 python 中运行?