Matplotlib and networkx merging Graphs when drawing
<p>I'm using <a href="https://networkx.readthedocs.io/en/stable/reference/drawing.html" rel="nofollow">Networkx</a> to visualise some graphs using the following code:</p>

<pre><code>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
</code></pre>

<p>Now the problem is that subsequent calls to <code>drawgraph</code>, will cause the drawn graphs to be merged with the previous ones e.g: if I call it twice, the first one is drawn correctly but the second picture contains the the first Graph in addition to the second Graph. Putting a <code>plt.show()</code> at the end of the function solves the Problem, however it's a blocking call and I can't have that. So how do I solve this Problem?</p>

<p>So after some looking around I found out the answer, I uncommented the <code>plt.figure()</code> line and added a <code>plt.close()</code> call at the end: </p>

<pre><code>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()
</code></pre>

python matplotlib networkx