Home > Software engineering >  How to assign colors and edges within a network through for loops
How to assign colors and edges within a network through for loops

Time:06-02

I am picturing an undirected graph by using a for loop for shrinking code rows. However, I am facing two problems

import networkx as nx
import matplotlib.pyplot as plt

G = nx.DiGraph()
G.add_nodes_from(range(1,8,1))

The colors I am trying to attribute to each node with the following loop do not appear in the final figure

color_list = []
for node in G.nodes:   # iteration over nodes
    if node < 4:
        color_list.append('gold')
    elif node >= 4: 
        color_list.append('violet')
    elif node == 6: 
        color_list.append('limegreen')
    else: 
        color_list.append('darkorange')   

I am struggling with creating an efficient loop to create edges within the following nodes (I have checked and applied many solutions, but I was not able to do this with a for loop)

G.add_edge(1,2)
G.add_edge(1,3)
G.add_edge(2,6)
G.add_edge(3,7)
G.add_edge(4,6)
G.add_edge(4,7)
G.add_edge(5,6)
     
#nx.draw(G, node_color = color_list, with_labels  =True)

pos = nx.spring_layout(G)

nx.draw_networkx_nodes(G, pos)
nx.draw_networkx_labels(G, pos)
nx.draw_networkx_edges(G, pos, edge_color='black')

plt.show()

This is the final figure I'm getting

enter image description here

Has anyone possibly have any suggestions? Just let me where these errors occur. Thanks

CodePudding user response:

You forgot to specify node_color=color_list while drawing the network. For instance, you cab use: nx.draw(G, pos, node_color=color_list,with_labels=True) to draw the network. You will then get the result below:

enter image description here

Also note that, as it stands, you will never get the colors limegreen and darkorange in your graph since the conditions node < 4 and node >= 4 are already partitioning the set of the nodes.

  • Related