如何通过回调更新PyQt中的散点图?

2024-04-26 20:34:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个程序,当用户点击一个按钮,我想用用户给出的新数据更新先前绘制的绘图。我要做的是向用户展示分类器系统的决策边界图,当用户添加新数据时,我想相应地更新散点图。我的代码是:

from matplotlib.backends.backend_qt5agg import (
    FigureCanvasQTAgg,
    FigureManagerQT,
)
from PyQt5 import QtWidgets
import matplotlib.pyplot as plt
from matplotlib.figure import Figure
import numpy as np
class CustomFigureCanvas(FigureCanvasQTAgg):
    def __init__(self, parent=None, cmap_name="coolwarm"):
        fig = Figure()
        self.color_map = plt.get_cmap(cmap_name)
        self.axes = fig.add_subplot(111)
        super().__init__(fig)
        self.setParent(parent)
        self.setBaseSize(300, 300)
        self.setMaximumSize(400, 400)
        self.setMinimumSize(250, 250)
        self.setSizePolicy(
            QtWidgets.QSizePolicy.MinimumExpanding,
            QtWidgets.QSizePolicy.MinimumExpanding,
        )

    def set_clf_2d(self, clf_2d):
        self.clf = clf_2d

    def plot_new_datapoints(self, x2D):
        self.add_datapoint(x2D)

    @staticmethod
    def _make_meshgrid(x, y, h=0.02):
        x_min, x_max = x.min() - 1, x.max() + 1
        y_min, y_max = y.min() - 1, y.max() + 1
        XX, YY = np.meshgrid(
            np.arange(x_min, x_max, h), np.arange(y_min, y_max, h)
        )
        return XX, YY

    def _plot_contours(self, xx, yy, **params):
        """Plot the decision boundaries for a classifier.

        Parameters
        ----------
        ax: matplotlib axes object
        clf: a classifier
        xx: meshgrid ndarray
        yy: meshgrid ndarray
        params: dictionary of params to pass to contourf, optional
        """
        Z = self.clf.predict(np.c_[xx.ravel(), yy.ravel()])
        Z = Z.reshape(xx.shape)
        self.axes.contourf(xx, yy, Z, **params)

    def plot_data(self, x2D, y):
        """plots the given array and the decision function bounday.

        Arguments:
            x2D {np.array} -- [2d array]
            y {np.array} -- [1d array]
        """

        x0, x1 = x2D[:, 0], x2D[:, 1]
        xx, yy = CustomFigureCanvas._make_meshgrid(x0, x1)
        labels = ["Cognitive", "Not Cognitive"]
        colors = ["r", "b"]
        self.axes.clear()
        self._plot_contours(xx, yy, cmap=self.color_map, alpha=0.8)
        target_ids = [0, 1]

        for i, c, label in zip(target_ids, colors, labels):
            print(i, label)
            self.axes.scatter(
                x0[y == i],
                x1[y == i],
                color=c,
                label=label,
                marker="o",
                s=(15, 15),
            )

        self.axes.set_xlim(xx.min(), xx.max())
        self.axes.set_ylim(yy.min(), yy.max())
        self.axes.set_title("2D Representation using PCA")
        self.axes.legend(fontsize=8)
        self.axes.plot()

    def add_datapoint(self, x2d):
        """Adds a new datapoint to the plot

        Arguments:
            x2d {a 2d single point, [x,y]} -- [np.array with shape (1,2)]
            axes {plt.axes} -- [description]

        """
        print(x2d, type(x2d))
        self.axes.scatter(
            x2d[:, 0],
            x2d[:, 1],
            color="k",
            label="Current Text",
            marker="o",
            s=(15, 15),
        )
        self.axes.legend(fontsize=8)
        self.axes.plot()

我当前遇到的问题是,在调用_plot_contours之后,绘图不会被更新。在阅读了matplotlib中的“可更新”图形之后,我看到一些建议使用plt.ion()来生成可更新的图形。还有一些关于使用FuncAnimation类的建议,但这并不是我所需要的解决方案,因为它不依赖用户的按钮单击回调,而是在给定的时间间隔内刷新绘图。在

编辑:这是一个最小的代码,它再现了我遇到的问题:

^{pr2}$

Tags: 用户selfplotmatplotlibdefnpminarray
2条回答

在matplotlib with Qt的情况下,必须刷新绘制,为此可以使用以下方法:

self.axes.figure.canvas.draw_idle()

或者

^{pr2}$

在您的情况下:

# ...

def _plot_contours(self, xx, yy, **params):
    # ...
    self.axes.contourf(xx, yy, Z, **params)
    self.axes.figure.canvas.draw()

def plot_data(self, x2D, y):
    # ...
    self.axes.plot()
    self.axes.figure.canvas.draw()

# ...

输出:

enter image description here

我不能确切地指出添加新数据点必须发生在什么地方,因为您的代码远没有最小值,但是这里有一个简单的例子来向qt应用程序中的散点图添加新点(尽管这实际上并不重要)。在

import sys
import numpy as np
from matplotlib.backends.backend_qt5agg import \
    (FigureCanvasQTAgg as FigureCanvas, NavigationToolbar2QT as NavigationToolbar)
from matplotlib.figure import Figure
from PyQt5 import QtCore, QtWidgets


class ApplicationWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super().__init__()
        self._main = QtWidgets.QWidget()
        self.setCentralWidget(self._main)
        layout = QtWidgets.QVBoxLayout(self._main)

        self.canvas = FigureCanvas(Figure(figsize=(5, 3)))
        layout.addWidget(self.canvas)
        self.addToolBar(QtCore.Qt.BottomToolBarArea,
                        NavigationToolbar(self.canvas, self))

        self.ax = self.canvas.figure.subplots()
        self.scat = self.ax.scatter([], [], marker='o', color='red', s=100)
        self.ax.set_xlim([0, 1])
        self.ax.set_ylim([0, 1])

        self.button = QtWidgets.QPushButton("Add point")
        self.button.clicked.connect(self.addPoint)
        layout.addWidget(self.button)

    def addPoint(self):
        x, y = np.random.random(size=(2,))
        old_data = self.scat.get_offsets()
        data = np.append(old_data, [[x, y]], axis=0)
        self.scat.set_offsets(data)
        self.canvas.draw_idle()


if __name__ == "__main__":
    qapp = QtWidgets.QApplication(sys.argv)
    app = ApplicationWindow()
    app.show()
    qapp.exec_()

相关问题 更多 >