2

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!

happy
  • 67
  • 7

1 Answers1

3

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:

enter image description here

jylls
  • 4,395
  • 2
  • 10
  • 21
  • But I also have a question when I code like this: [my code](https://github.com/catbao/test2/blob/main/c3900c5d29bc6b0f8d4753e71c3b662.jpg) The result is like this: [the result](https://github.com/catbao/test2/blob/main/f025e41fdc37761d401931cff5896f2.jpg). It looks like the edges and the vertices are separate. Why this appear? How can I solve it? – happy Aug 31 '22 at 14:06
  • It looks like only circular_layout works? And if I use spring_layout, it will be that case. – happy Aug 31 '22 at 14:13
  • It should work with all possible layouts. You just need to make sure that you pass the same node positions to `nx.draw_networkx_nodes` and `nx.draw_networkx_edges` . `nx.spring_layout` has some randomness associated to it (`nx.circular_layout` doesn't). Which means that calling it twice will output two different layouts. It's best to store the node positions in a variable and then pass it to the two drawing functions. See edit of my answer for more details. – jylls Aug 31 '22 at 14:35