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>Any time you plot something and then plot something again, with <code>matplotlib.pyplot</code>, both things will appear.  You need to close or clear the figure.</p>

<p>Adding <code>plt.clf()</code> to clear the figure will solve the problem.  I don't believe <code>plt.draw()</code> does anything for you.</p>

python matplotlib networkx