Search code examples
pythonpandasfor-loopnetworkx

Creating several graphs using 'for' loop


I have a dataset that looks like

Node  Target Group
A       B      1
A       C      1
B       D      2
F       E      3
F       A      3
G       M      3

I would like to create a graph for each distinct value in Group. There are 5 groups in total.

file_num = 1
for item <=5: # this is wrong
    item.plot(title='Iteration n.'+item)
    plt.savefig(f'{file}_{file_num}.png')
    file_num += 1

    G = nx.from_pandas_edgelist(df, source='Node', target='Target')

    cytoscapeobj = ipycytoscape.CytoscapeWidget()
    cytoscapeobj.graph.add_graph_from_networkx(G)
    cytoscapeobj

This code, however, does not generate individual graphs (G and the objet from Cytoscape), meaning that something does not work within the loop (at least). Any help would be extremely useful.


Solution

  • Let's call the DataFrame df. Then you iterate over the unique values in the Group column, subset df by this Group value, and save a new figure each iteration of the loop.

    file_num = 1
    for group_val in df.Group.unique():
        df_group = item[item['group'] == group_val]
        df_group.plot(title='Iteration n.'+item)
        plt.savefig(f'{file}_{file_num}.png')
        file_num += 1
    
        G = nx.from_pandas_edgelist(df_group, source='Node', target='Target')
    
        cytoscapeobj = ipycytoscape.CytoscapeWidget()
        cytoscapeobj.graph.add_graph_from_networkx(G)
        cytoscapeobj