Python networkx graph: Don't draw old graph along with new graph

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. 0.png has one line AB, but 1.png has two lines: AB and AC. It looks like the memory for 0.png is not cleared, although I have "G.clear ()".

Does anyone know how to fix it?

+3


source to share


1 answer


I have a solution.



Add plt.clf()

after plt.savefig(str(i) + ".png")

. It can clean up the old plot in pyplot. Hope this can help someone.

+15


source







All Articles