Andrew Earl
Andrew Earl

Reputation: 363

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!

Upvotes: 0

Views: 8898

Answers (3)

Kristina Sebastian
Kristina Sebastian

Reputation: 11

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(1 for line in open(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

Upvotes: 1

Mohammad Athar
Mohammad Athar

Reputation: 1980

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

Upvotes: 3

David Cox
David Cox

Reputation: 41

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 in enumerate(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")                     

Upvotes: 1

Related Questions