Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python networkx graph: Do not draw old graph together with new graph

Tags:

networkx

The below is my code:

import networkx as nx
for i in range(2):
    G = nx.DiGraph()
    if i==0:
        G.add_edge("A", "B")
    elif i==1:
        G.add_edge("A", "C")
    import matplotlib.pyplot as plt
    nx.draw(G)
    plt.savefig(str(i)+".png")
    G.clear()

It should draw line AB in file 0.png and draw line AC in file 1.png. But, after I ran it. In 0.png, there is one line AB, but in 1.png, there are two lines: AB and AC. It seems that the memory for 0.png is not cleaned, although I have had "G.clear()".

Does anybody know how to fix it?

like image 251
Munichong Avatar asked Mar 21 '12 21:03

Munichong


1 Answers

I have got the solution.

Add plt.clf() after plt.savefig(str(i) + ".png"). It can clean the old graph in pyplot. I hope it can help someone.

like image 159
Munichong Avatar answered Oct 04 '22 05:10

Munichong