2012-03-08 102 views
3

根據我對使用matplotlib的基本理解,您將所需的plt存儲在某個'fig'中,然後可以使用canvas.draw()操作繪製所述'fig'。如果是這種情況,那麼我不應該有任何問題,但是因爲我這樣做了,到底發生了什麼以及在畫布上獲得某些東西的邏輯是什麼。另外,我的最終目標是在QtPy窗口中顯示此圖。迄今爲止的結果是,我可以讓窗口和畫布顯示,但畫布顯示爲空。我一直在尋找http://matplotlib.sourceforge.net/users/artists.html,覺得我所做的並不完全錯誤,但也許我忽略了一些細微差別。這裏是代碼,我引用:Can not get canvas to draw fig in matplotlib

def drawThis(self): 

     self.axes.clear() 
     self.axes.grid(self.grid_cb.isChecked()) 
     self.fig = plt.figure(figsize=(11,7),dpi=self.dpi) 
     file = fileList[selFile] 
     valid = [sColumn] 
     matrix = np.loadtxt(file, skiprows=1, usecols=valid) 
     colCount = np.loadtxt(file, dtype=object) 
     totalCols = colCount.shape[1] 

     kdeData = np.array(matrix) 
     dataRange = (Decimal(max(abs(kdeData)))/10).quantize(1, rounding=ROUND_UP) * 10 

     gkde = stats.gaussian_kde(kdeData) 
     ind = np.linspace(-int(dataRange), int(dataRange), len(kdeData) * sSamples) 
     kdepdf = gkde.evaluate(ind) 

     ##plot histogram of sample 
     plt.hist(kdeData, len(kdeData), normed=1, alpha=0.20) 
     ##plot data generating density 
     plt.plot(ind, stats.norm.pdf(ind), 'r', linewidth=0.8, label='DGP normal') 
     ##plot estimated density 
     plt.plot(ind, kdepdf, 'g', linewidth=0.8, label='kde') 
     plt.title('KDE for '+ str(nameList[selFile])) 
     plt.legend() 

     self.fig.canvas.draw() 

回答

2

我沒有與任何matplotlib經驗,但在看着你的代碼,我不知道你的pyplot使用是正確的?你的代碼在我看來的方式是,你使用pyplot來產生數據(你不保留返回值),然後你繪製它,但我認爲它實際上並沒有在你的軸實例上運行。

一個我如何看到matplotlib被使用的例子可以在這裏找到:Segfault using matplotlib with PyQt ..其中他實際上是直接創建一個PyQt4 FigureCanvas並直接繪製到他的軸實例。

看來pyplot.plot()方法可以採用圖形和軸參數來告訴它使用哪個實例。我不知道它是不是使用你的軸,因爲我看不到你的例子如何創建軸本身。採取在看看docs here

我的猜測是,你可以嘗試做這樣的事情:

plt.plot(ind, kdepdf, 'g', axis=self.axis, linewidth=0.8, label='kde') 

或者,也許確認您有createe self.axis使用self.axis = plt.axis(),甚至嘗試做所有你直接與繪圖軸實例?

+0

我想我誤解了在我正在創建的窗口中實例化圖的過程。我實際上使用了在示例中找到的一部分代碼來創建我正在做的事情,但我一直將plt中的情節存儲在不在「self.axes」上,這是實際顯示在畫布上的那個。在你提到我沒有對我使用pyplot生成的數據做任何事情後,終於意識到這一點,謝謝。 – DamianJ 2012-03-08 05:08:15