在多个地方嵌入matplotlib小部件

时间:2011-12-30 06:24:00

标签: python matplotlib pyqt

我有一个matplotlib图,我想在两个单独的窗口中重复,在PyQt4下。我已经尝试将小部件添加到两者的布局中,但随后小部件从第一个小部件消失。有没有办法做到这一点,除了创建两个相同的图并保持同步?

2 个答案:

答案 0 :(得分:2)

问题在于你无法将相同的qt小部件添加到两个不同的父窗口小部件中,因为在添加小部件的过程中,Qt还会创建一个重复的过程,它会执行您所看到的内容:

  

......小部件从第一个[窗口]消失......

因此,解决方案是制作两个共享相同图形的画布。 这是一个示例代码,这将显示两个主窗口,每个窗口有两个画布,四个图将同步:

import sys
from PyQt4 import QtGui
import numpy as np
import numpy.random as rd
from matplotlib.figure import Figure
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas

class ApplicationWindow(QtGui.QMainWindow):

    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        self.main_widget = QtGui.QWidget(self)
        vbl = QtGui.QVBoxLayout(self.main_widget)

        self._fig = Figure()        
        self.ax = self._fig.add_subplot(111)

        #note the same fig for two canvas
        self.fc1 = FigureCanvas(self._fig) #canvas #1
        self.fc2 = FigureCanvas(self._fig) #canvas #1

        self.but = QtGui.QPushButton(self.main_widget)
        self.but.setText("Update") #for testing the sync

        vbl.addWidget(self.fc1)
        vbl.addWidget(self.fc2)
        vbl.addWidget(self.but)        

        self.setCentralWidget(self.main_widget)

    @property  
    def fig(self):
        return self._fig

    @fig.setter
    def fig(self, value):
        self._fig = value
        #keep the same fig in both canvas
        self.fc1.figure = value
        self.fc2.figure = value        

    def redraw_plot(self):
        self.fc1.draw()
        self.fc2.draw()


qApp = QtGui.QApplication(sys.argv)

aw1 = ApplicationWindow() #window #1
aw2 = ApplicationWindow() #window #2

aw1.fig = aw2.fig #THE SAME FIG FOR THE TWO WINDOWS!

def update_plot():
    '''Just a random plot for test the sync!'''
    #note that the update is only in the first window
    ax = aw1.fig.gca()
    ax.clear()
    ax.plot(range(10),rd.random(10))

    #calls to redraw the canvas
    aw1.redraw_plot()
    aw2.redraw_plot()

#just for testing the update
aw1.but.clicked.connect(update_plot)
aw2.but.clicked.connect(update_plot)        

aw1.show()
aw2.show()

sys.exit(qApp.exec_())

答案 1 :(得分:0)

虽然它不是一个完美的解决方案,但matplotlib有一种内置的方法可以保持两个独立图表的限制,滴答等同步。

E.g。

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 4 * np.pi, 100)
y = np.cos(x)

figures = [plt.figure() for _ in range(3)]
ax1 = figures[0].add_subplot(111)
axes = [ax1] + [fig.add_subplot(111, sharex=ax1, sharey=ax1) for fig in figures[1:]]

for ax in axes:
    ax.plot(x, y, 'go-')

ax1.set_xlabel('test')

plt.show()

请注意,缩放,平移等所有3个绘图都将保持同步

虽然可能有更好的方法。