Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drawing a large weighted network in networkx based on thickness?

How do I draw a weighted network of N>1000 nodes in networkx by thickness? If I have a .csv list of source, target nodes and the weight for each edge, and I am thinking of using the method:

for i in range(N)
G.add_edge(source[i],target[i], weight=weight[i]) 
nx.draw_networkx_edges(G)

but then, do I have to give thickness to every edge? or every group of edges with similar thickness?

like image 339
user3298574 Avatar asked Dec 12 '22 07:12

user3298574


1 Answers

You can specify each edge individually, or you can define them in groups if you have some function to compute groupings (and then use multiple calls to draw_network_edges).

Here's an example with a random graph that uses the edge weights as is, first to define the edge thickness and second, using the data as coloring instead.

import matplotlib.pyplot as plt
import networkx as nx
import numpy as np

n = 15; m = 40

# select some edge destinations
L = np.random.choice(xrange(n), 2*m)
# and suppose that each edge has a weight
weights = 0.5 + 5 * np.random.rand(m)

# create a graph object, add n nodes to it, and the edges
G = nx.DiGraph()
G.add_nodes_from(xrange(n))
for i, (fr, to) in enumerate(zip(L[1::2], L[::2])):
  G.add_edge(fr, to, weight=weights[i])

# use one of the edge properties to control line thickness
edgewidth = [ d['weight'] for (u,v,d) in G.edges(data=True)]

# layout
pos = nx.spring_layout(G, iterations=50)
#pos = nx.random_layout(G)

# rendering
plt.figure(1)
plt.subplot(211); plt.axis('off')
nx.draw_networkx_nodes(G, pos)
nx.draw_networkx_edges(G, pos, width=edgewidth,)

plt.subplot(212); plt.axis('off')

# rendering
nx.draw_networkx_nodes(G, pos)
nx.draw_networkx_edges(G, pos, edge_color=edgewidth)

plt.show()

Which gives you something like this: thickness / coloring of edges

Clearly you could use a more complicated function to assemble the list of edgewidth values as suitable to your application (e.g. binned values or a product of different properties) as well.

like image 76
Bonlenfum Avatar answered Apr 16 '23 14:04

Bonlenfum