Andrew Earl Andrew Earl - 3 months ago 28
Python Question

How do I save a new graph as png with every iteration of a loop

I don't know how to save a new graph png for each iteration of a loop using NetworkX. I've borrowed the code from this question: in NetworkX cannot save a graph as jpg or png file and manipulated it a bit. Below is the code:

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


Ideally I would like to have four images each one with different color nodes. Let me know if you need any more information. Thanks!

Answer

Just change the name of the output file

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" + str(n) +".png", format="PNG")
    n += 1

You should use more descriptive names though. Maybe instead of n, you could refer to a time

    plt.savefig("Graph" + str(datetime.datetime.now()) +".png", format="PNG")

That isn't great, since the string will have whitespace, but you can tweak it beforehand