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

梦想的初衷 提交于 2021-01-22 12:12:30

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/9812996/python-networkx-graph-do-not-draw-old-graph-together-with-new-graph

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!