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
Solution 1:
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
Solution 2:
First suggestion, accessing the colors by their index values is not "Pythonic". Instead, use a for
loop:
for color in colors:
print(color)
Your code is overwriting Graph.png
on each iteration of the loop. To save a new file for each iteration, simply rename the output file on each iteration. One way to do this is by using the format() and enumerate() functions:
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)
colors = ['yellow', 'red', 'blue', 'green']
for i, color inenumerate(colors):
nx.draw(G, pos, node_size=1500, node_color=color, font_size=8, font_weight='bold')
plt.tight_layout()
plt.savefig('Graph_{}.png'.format(i), format="PNG")
Solution 3:
By the way, I just used this method and I added a step futher for my labels to be from my filename. I hope it helps someone.
files = glob.glob(folder+'\\'+'*.csv', recursive=False)
for file in files:
df1=pd.read_csv(file,header=1,sep=',')
nslice = (sum(1for line inopen(file))-1)/3
base = print(os.path.splitext(os.path.basename(file))[0])
fig = plt.figure()
ax = plt.subplot(111)
c = ax.plot(df1.iloc[0:int(nslice)-1,[22]],df1.iloc[0:int(nslice)-1,[4]],label='Cuticle')
t = ax.plot(df1.iloc[int(nslice):(int(nslice)-1)*2,[22]],df1.iloc[int(nslice):(int(nslice)-1)*2,[4]],label='Tissue')
p = ax.plot(df1.iloc[int(nslice)*2:(int(nslice)-1)*3,[22]],df1.iloc[int(nslice)*2:(int(nslice)-1)*3,[4]],label='Phenanthrene')
title_obj = plt.title(base)
plt.xlabel("Slice #")
plt.ylabel("Avg MGV")
ax.legend()
plt.savefig('plot'+str(os.path.splitext(os.path.basename(file))[0])+'.png')
plt.show()
plt.close('all')
Peace
Post a Comment for "How Do I Save A New Graph As Png With Every Iteration Of A Loop"