简体   繁体   English

PyQt和Matplotlib:创建图的副本

[英]PyQt and Matplotlib: creating a copy of a plot

I am new to matplotlib and I have been struggling with implementing a feature for quite some time. 我是matplotlib的新手,并且在相当长时间内一直在努力实现该功能。 Basically I have a plot embedded into a widget and I want to (on button press) create a new Widget with this exact same plot on it. 基本上,我有一个嵌入到窗口小部件中的图,我想(按一下按钮)创建一个新的窗口小部件,上面有完全相同的图。 Is there an easy way to do this? 是否有捷径可寻? [Assuming I already have all the action handlers implemented] [假设我已经实现了所有动作处理程序]

The following is butchered from the embedding_in_qt4 example of matplotlib 以下内容来自matplotlib的embedding_in_qt4示例

import sys
from PyQt4 import QtGui, QtCore

from numpy import arange, sin, pi
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure


class MyMplCanvas(FigureCanvas):
    """Ultimately, this is a QWidget (as well as a FigureCanvasAgg, etc.)."""
    def __init__(self, parent=None, width=5, height=4, dpi=100):
        fig = Figure(figsize=(width, height), dpi=dpi)
        self.fig = fig
        self.axes = fig.add_subplot(111)
        # We want the axes cleared every time plot() is called
        self.axes.hold(False)

        self.compute_initial_figure()
        FigureCanvas.__init__(self, fig)
        self.setParent(parent)

        FigureCanvas.setSizePolicy(self,
                                   QtGui.QSizePolicy.Expanding,
                                   QtGui.QSizePolicy.Expanding)
        FigureCanvas.updateGeometry(self)

    def compute_initial_figure(self):
        pass


class MyStaticMplCanvas(MyMplCanvas):
    """Simple canvas with a sine plot."""
    def compute_initial_figure(self):
        t = arange(0.0, 3.0, 0.01)
        s = sin(2*pi*t)
        self.axes.plot(t, s)


class ApplicationWindow(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.setAttribute(QtCore.Qt.WA_DeleteOnClose)
        self.main_widget = QtGui.QWidget(self)
        l = QtGui.QVBoxLayout(self)
        sc = MyStaticMplCanvas(self, width=5, height=4, dpi=100)
        self.sc = sc
        l.addWidget(sc)
        but = QtGui.QPushButton("make_new", self)
        but.clicked.connect(self.again)
        l.addWidget(but)

    def again(self):
        win = MyMplCanvas()
        win.fig = self.sc.fig
        FigureCanvas.__init__(win, win.fig)
        self.win = win
        win.show()

qApp = QtGui.QApplication(sys.argv)
aw = ApplicationWindow()
aw.show()
sys.exit(qApp.exec_())

Note how the canvas keeps a reference to its figure object and the application keeps a reference to the new canvas. 请注意画布如何保留对其图形对象的引用,而应用程序如何保留对新画布的引用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM