图表保持增长,即使在清除之后

时间:2015-08-29 14:10:43

标签: python matplotlib networkx

我正在尝试使用此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())

结果如下图所示:

[This graph is correct] [This one is not. The outlying point should be the only element present in the graph]

我已经通过Stackoverflow和matplotlib文档进行了大量挖掘,但一直无法找到任何有用的东西。任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:3)

使用Graph.clear()后,所有节点和边缘都已从图表中删除。您可以在致电K_5.number_of_nodes()后打印Graph.clear()进行检查。然而,在你绘制第一个数字后,你不能清除它,因此,它会在第一个数字之上绘制。

所以你需要清除matplotlib的当前数字。您可以使用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:

enter image description here

<强> test2.png:

enter image description here

相关问题