【发布时间】:2016-08-11 19:17:09
【问题描述】:
我不知道如何使用 NetworkX 为循环的每次迭代保存一个新的图形 png。我从这个问题中借用了代码:in NetworkX cannot save a graph as jpg or png file 并对其进行了一些操作。下面是代码:
import networkx as nx
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(12,12))
ax = plt.subplot(111)
ax.set_title('Graph - Shapes', fontsize=10)
G = nx.DiGraph()
G.add_node('shape1', level=1)
G.add_node('shape2', level=2)
G.add_node('shape3', level=2)
G.add_node('shape4', level=3)
G.add_edge('shape1', 'shape2')
G.add_edge('shape1', 'shape3')
G.add_edge('shape3', 'shape4')
pos = nx.spring_layout(G)
n = 0
colorses = ['yellow', 'red', 'blue', 'green']
while n < len(colorses):
nx.draw(G, pos, node_size=1500, node_color=colorses[n], font_size=8, font_weight='bold')
plt.tight_layout()
# plt.show()
plt.savefig("Graph.png", format="PNG")
n += 1
理想情况下,我希望有四张图片,每张图片都有不同的颜色节点。如果您需要更多信息,请告诉我。谢谢!
【问题讨论】:
-
嗯...如果每次迭代都更改文件名怎么办,所以让
"Graph.png"依赖于n,比如plt.savefig("Graph{}.png".format(n), format="PNG")?
标签: python matplotlib networkx