简体   繁体   中英

Graph Keeps Growing, Even After Clearing It

I am trying to graph two different graphs using this Python program:

K_5=nx.complete_graph(10)
print(K_5.number_of_nodes(), K_5.number_of_edges())
nx.draw(K_5)
plt.savefig('test1.png')
K_5.clear()
G = nx.Graph()
G.add_node(8)
nx.draw(G)
plt.savefig('test2.png')
print(G.number_of_nodes(), G.number_of_edges())

Which results in the following graphs:

[ 此图是正确的] [ 这不是。外围点应该是图形中存在的唯一元素]

I have done quite a bit of digging through Stackoverflow and the matplotlib documentation, but have been unable to find anything useful. Any help would be much appreciated!

After you use Graph.clear() , all the nodes and edges already removed from your graph. You can check it by printing K_5.number_of_nodes() after you call Graph.clear() . However, after you plot the first figure, you don't clear it, hence, it plots on top of the first figure.

So you need to clear the matplotlib's current figure. You can use plt.clf() .

import networkx as nx
import matplotlib.pyplot as plt

K_5=nx.complete_graph(10)
print(K_5.number_of_nodes(), K_5.number_of_edges())
nx.draw(K_5)
plt.savefig('test1.png')
K_5.clear()

plt.clf() # new line, to clear the old drawings

G = nx.Graph()
G.add_node(8)
nx.draw(G)
plt.savefig('test2.png')
print(G.number_of_nodes(), G.number_of_edges())

test1.png:

在此处输入图片说明

test2.png:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM