绘图时Matplotlib和networkx合并图形

时间:2016-09-20 08:18:21

标签: python matplotlib networkx

我使用Networkx使用以下代码可视化某些图表:

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会导致绘制的图形与之前的图形合并,例如:如果我调用它两次,第一个被正确绘制但第二个图片包含第一个Graph除了第二个Graph之外。在函数末尾放置一个plt.show()可以解决问题,但是它是一个阻塞调用而我无法做到这一点。那么我该如何解决这个问题?

2 个答案:

答案 0 :(得分: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()

答案 1 :(得分:0)

任何时候你用matplotlib.pyplot绘制一些东西,然后重新绘制一些东西,两件事都会出现。你需要关闭或清除这个数字。

添加plt.clf()以清除图形将解决问题。我不相信plt.draw()会为你做任何事情。