简体   繁体   English

即使清除后图形仍保持增长

[英]Graph Keeps Growing, Even After Clearing It

I am trying to graph two different graphs using this Python program: 我正在尝试使用此Python程序绘制两个不同的图:

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. 我已经大量研究了Stackoverflow和matplotlib文档,但是找不到任何有用的东西。 Any help would be much appreciated! 任何帮助将非常感激!

After you use Graph.clear() , all the nodes and edges already removed from your graph. 使用Graph.clear() ,所有已从图形中删除的节点和边。 You can check it by printing K_5.number_of_nodes() after you call Graph.clear() . 您可以在调用Graph.clear()之后通过打印K_5.number_of_nodes()进行检查。 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. 因此,您需要清除matplotlib的当前数据。 You can use plt.clf() . 您可以使用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: test1.png:

在此处输入图片说明

test2.png: test2.png:

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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