osmak osmak - 2 years ago 398
Python Question

Python networkx: node are not taking color list

I started learning Python to use networkx. I am trying to build a hierarchy rooted at some node (node 0), and I want the colors to change according to distance (in hops) from that node. I have written the following code, but I don't know why the colors are not changing!! can you please point out the problem?

import networkx as nx
import matplotlib.pyplot as plt
import matplotlib.cm as cmx
import random

# initial values of rings in nodes
MAX_RING = 1000

class Node:
count = int(0)
tx_range = 3
def __init__(self, i):
Node.count+= 1
self.id = int(i)
self.ring = int(MAX_RING)
self.x_pos = int()
self.y_pos = int()
self.parent_list = list()
self.nbr_list = list()
self.color = float()

def addNbr(self, nbr):

def createNodes(Nodes, pos, labels):
for i in range(num_of_nodes):
Nodes[i].x_pos = random.randrange(net_width)
Nodes[i].y_pos = random.randrange(net_hieght)
pos[i] = (Nodes[i].x_pos, Nodes[i].y_pos)
labels[i] = i

def createEdges(Graph, Nodes, Edges):
for i in range(num_of_nodes):
for j in range(i + 1, num_of_nodes):
dist = ((Nodes[i].x_pos - Nodes[j].x_pos)**2 + (Nodes[i].y_pos - Nodes[j].y_pos)**2) ** 0.5
if dist <= Node.tx_range:
Graph.add_edge(i, j)
#Graph.add_edge(j, i)
Edges.append((i , j))
print("Edge added")

def createRings(G, Nodes, colors, VisEdges):
# Base station is node 0 and has ring 0
# find all nodes in current ring and check their neighbors to create the next ring
# next ring becomes current ring and repeat from previous step
current_ring = 0
current_node = Nodes[0]
current_node.ring = current_ring
# temporary set to travers all nodes initially contains the BS
N = [Nodes[0]]
while len(N) > 0:
node = N.pop(0)
for nbr in node.nbr_list:
# for each node check if it has a neighbor with ring less than MAX_RING
if nbr.ring > node.ring + 1:
if(nbr.ring != MAX_RING):
nbr.ring = node.ring + 1
nbr.color = nbr.ring
VisEdges.append((node.id, nbr.id))
for node in Nodes:
colors.insert(node.id, node.color)

def main():
Nodes = list()
Edges = list()
VisEdges = list()
pos = dict()
labels = {}
colors = []
G = nx.Graph()
createNodes(Nodes, pos, labels)
createEdges(G, Nodes, Edges)
for n, p in pos.items():
G.node[n]['pos'] = p

createRings(G, Nodes, colors, VisEdges)
colors[0] = 1
for node in Nodes:
print('Node[',node.id,'] ring is ', node.ring, 'color is', colors[node.id])

nx.draw(G,pos, edgelist=VisEdges, nodelist=pos.keys() , node_colors=colors, cmap=cmx.get_cmap('Reds'),
vmin=0, vmax=max(colors))


num_of_nodes = 100
net_width = 15
net_hieght = 15

Answer Source

You have a typo in your argument list to nx.draw(). It should be node_color, i.e.

nx.draw(G,pos, edgelist=VisEdges, nodelist=pos.keys() , node_color=colors, cmap=cmx.get_cmap('Reds'),
        vmin=0, vmax=max(colors))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download