Reputation: 19375
I am importing a csv file called network_nodes
which looks like
['151753', '111598', '0.211413517594337', '-0.130335792899132']
['151753', '118516', '0.211413517594337', '-0.100253812968731']
where the first two columns indicate nodes
, and the 2 last columns are values
associated with those nodes.
For instance, here the node called '151753'
is connected to the node called '111598'
and '118516'
. And the node '151753'
is associated with a value
of '0.211413517594337', while '111598'
is associated with a value
of -0.130335792899132'.
I would like to plot this network in Networkx, using a different color (or node size) according to the node values (for instance red/big when the value is very high, blue/small when it is very low).
I do not know how to do this. I know that I should use something like
G=nx.read_adjlist('network_nodes.csv', delimiter=',')
nx.draw(G)
but the read_adjlist function do not allow me to import node values...
Upvotes: 2
Views: 1114
Reputation: 2127
Aric is right that you need to write some custom code, but since you have a list of edges, and not a list of nodes, the following code will work better.
import csv
import networkx as nx
G = nx.DiGraph()
with open('network_nodes.csv') as f:
node_list = csv.reader(f)
for row in node_list:
G.add_edge(row[0],row[1])
G.node[row[0]]['value'] = float(row[2])
G.node[row[1]]['value'] = float(row[3])
G.nodes(data=True) #print out
Prints the following:
[('151753', {'value': 0.211413517594337}),
('118516', {'value': -0.100253812968731}),
('111598', {'value': -0.130335792899132})]
Upvotes: 3
Reputation: 1512
The lines you quoted aren't in csv file format. Assuming you prefer having ints and floats instead of strings, this would be the data in correct csv format :
151753,111598,0.211413517594337,-0.130335792899132
151753,118516,0.211413517594337,-0.100253812968731
Either you can load your data as list, not using a csvreader, or you can convert your files with the following sed commands
sed -i.bak "s/\[\(.*\)\]$/\1/" network_nodes
sed -i.bak "s/'\([0-9\.-]*\)'/\1/g" network_nodes
.bak
files are temporary backup files you can use to rollback a sed command. Remove them when you are done. Loading graph data with the csv loader should succeed after doing this.
Upvotes: 1
Reputation: 25289
You will need to write something custom to read your file. Here is one way:
node,weight,color
1,7.0,r
2,42,g
3,1,b
--
import csv
import networkx as nx
import matplotlib.pyplot as plt
G = nx.Graph()
with open('nodelist.txt') as f:
reader = csv.DictReader(f)
for row in reader:
node = int(row.pop('node'))
G.add_node(node, **row)
print G.nodes(data=True)
# [(1, {'color': 'r', 'weight': '7.0'}), (2, {'color': 'g', 'weight': '42'}), (3, {'color': 'b', 'weight': '1'})]
And drawing
nodes = G.nodes()
color = [G.node[n]['color'] for n in nodes]
size = [float(G.node[n]['weight'])*100 for n in nodes]
nx.draw(G, nodes=nodes,node_color=color, node_size=size)
plt.show()
Upvotes: 4