2016-09-20 118 views
0

當我使用Networkx使用下面的代碼,以可視化一些圖表networkx合併圖:Matplotlib和繪圖

import networkx as nx 
import matplotlib.pyplot as plt 

def drawgraph(g, filename): 
    #plt.figure() I had to comment this line because it gives me an 'alloc: invalid block` error 
    nx.draw(g) 
    plt.draw() # I added this hoping it might solve the problem (outlined in the text below the code) 
    plt.savefig(filename) 
    #plt.show() this solves the problem, however it's blocking call and I'm drawing hundreds of graphs 

現在的問題是,之後drawgraph調用,將導致繪製的圖表與合併以前的例如:如果我稱它爲兩次,第一個繪製正確,但第二個圖片包含除第二個圖之外的第一個圖。在函數的末尾放置一個plt.show()可以解決問題,但是這是一個阻塞調用,我不能這樣做。那麼我該如何解決這個問題?

回答

0

所以經過一些環顧四周,我發現了答案,我註釋掉了plt.figure()線,並在末尾加上一個plt.close()電話:

import networkx as nx 
import matplotlib.pyplot as plt 

def drawgraph(g, filename): 
    plt.figure() 
    nx.draw(g) 
    plt.draw() 
    plt.savefig(filename) 
    plt.close() 
0

任何時候你畫出的東西,然後再繪製的東西,與matplotlib.pyplot,這兩件事情都會出現。您需要關閉或清除該圖。

添加plt.clf()來清除數字將解決問題。我不相信plt.draw()會爲你做任何事情。