I am new to matplotlib and I have been struggling with implementing a feature for quite some time. 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]
Asked
Active
Viewed 562 times
1 Answers
0
The following is butchered from the embedding_in_qt4
example of matplotlib
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.

mdurant
- 27,272
- 5
- 45
- 74