Reputation: 1
Here's the part of the code where I try to add the color attribute. So the nodes will be coloured with 4 different colors: the best fitness, the worse, top 10% best fitness and 10% worse.
for i in range(len(nodes)):
if nodes[i]==top:
NetGraph.node[i]['color']='r'
Hope you can help me! Cheers
Upvotes: 0
Views: 1474
Reputation: 2368
If you are trying to "merge" relationship data that are stored in a number of different .nodes' and
.edges' files into one graph, then it is possible that as the files are read from the disk you come across a node that has not yet been added to the graph.
In general, I feel that more information is required to provide a more meaningful answer to this question. For example: what is the format of the .node
and .edge
files? What is in the top
variable? (Is that a list or a single number variable representing a threshold?).
However, based on what is mentioned so far in this question, here are a few pointers:
Try to build the graph first and colour it later. This might appear inneficient if you already have the fitness data but it will be the easiest way to get you to a working piece of code.
Make sure that your node IDs are indeed integer numbers. That is, each node, is known in the graph, by its index value. For example 2,3,5, etc instead of "Paris", "London", "Berlin", etc (i.e. string node IDs). If it is the latter, then the for would be better formed as: for aNode in G.nodes(data = True):
. This will return an iterator with each node's ID and a dictionary with all of the existing node's data.
If top
is a single variable, then it doesn't make sense to compare the node's ID with the top
threshold. It would be like saying if 22 (which is a node ID) is equal to 89 (which is some expression of efficiency) then apply the red colour to the node. If top
is a list that contains all the nodes that are considered top nodes, then the condition expression should have been: if nodes[i] in top:
.
You seem to have skipped an indentation below the if
(?). For the statement that assigns the colour to the node provided that the condition is True
, to work, it needs to be indented one more set of 4 spaces to the right.
The expression to assign the colour is correct.
Please note that Networkx will make an attempt to write every node and edge attribute it comes across in a Graph to the appropriate format. For more information on this, please see the response to this question. Therefore, once you are satisfied with the structure of a given graph (G), then you can simply call networkx.write_graphml(G, 'mygraph.gml')
to save it to the disk (where networkx
is the name of the module). The networkx.write_*
functions will export a complete version of your graph (G) to a number of different formats or raise an exception if a data type cannot be serialised properly.
I hope this helps. Happy to ammend the response if more details are provided later on.
Upvotes: 2