我是matplotlib的新手,我一直在努力实现一项功能。基本上我有一个嵌入到小部件中的绘图,我想(按下按钮)创建一个新的小部件,上面有相同的绘图。是否有捷径可寻? [假设我已经实现了所有的动作处理程序]
答案 0 :(得分:0)
以下是来自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_())
请注意画布如何保持对其图形对象的引用,并且应用程序保留对新画布的引用。