2011-12-30 32 views
4

我有一個matplotlib圖形,我想在PyQt4下的兩個獨立窗口中重複使用它。我已經嘗試將小部件添加到兩者的佈局中,但隨後小部件從第一個中消失。除了創建兩個相同的圖並保持同步外,是否有任何方法可以實現這一點?在多個位置嵌入matplotlib小部件

回答

0

雖然它不是一個完美的解決方案,但matplotlib有一個內置的方法來保持兩個獨立圖的同步極限,滴答等。

例如

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個地塊將保持同步,相位等

有可能,雖然這樣做的更好的方法。

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_())