I'm tring draw a graph in networkx and at the same time, calculate edge betweenness centrality of every edge, using this to set a different transparency for each edge. My code looks like this:
G = nx.gnp_random_graph(10,0.5)
options = {
'node_color':'black',
'node_size':1,
'alpha':0.2
}
edge_betweenness_centrality(G)
nx.draw(G,**options)
plt.show()
Where the first line is to generate a random graph with 10 nodes, and the edge_betweenness_centrality(G)
calculate edge betweenness of every edge.The output just like this:
the output of edge_betweenness_centrality(G)
And what I want to do is set the transparency of every edge using the above output. I can only set the unity transparency in options just like the above code 'alpha':0.2
. So,how do I achieve that?
Can someone help me? I will be very grateful!
Since the alpha
value in nx.draw_network_edges
can only be a float and not a list or dictionnary (doc here), you will probably have to loop through your edges and draw each edge seperately. You can specify the edge in the edgelist
argument and change the alpha
value iteratively.
See code below:
import networkx as nx
import matplotlib.pyplot as plt
import numpy as np
G = nx.gnp_random_graph(10,0.5)
options = {
'node_color':'black',
'node_size':200
}
cent=nx.edge_betweenness_centrality(G)
node_pos=nx.circular_layout(G) #Any layout will work here, including nx.spring_layout(G)
nx.draw_networkx_nodes(G,pos=node_pos,**options)#draw nodes
[nx.draw_networkx_edges(G,pos=node_pos,edgelist=[key],alpha=np.amin([value*10,1]),width=5) for key,value in cent.items()] #loop through edges and draw them
plt.show()
And the output gives: