Home > database >  Colouring edge of network based on their direction - NetworkX
Colouring edge of network based on their direction - NetworkX

Time:02-23

In R ggplot2, there is a simple way to color the edge of a network based on its direction between nodes. So if a line (edge) is directed from the nodes A to B, we can use the code:

geom_edge(aes(colour=stat(index))

Then I tried to redo this in python using NetworkX - to no avail. Here is an example network:

F.add_nodes_from([0,1])
F.add_nodes_from([0,2])
F.add_nodes_from([2,1])
post = nx.circular_layout(F)
nx.draw_networkx_nodes(F, post, node_color = 'r', node_size = 100, alpha = 1)
nx.draw_networkx_edges(F, post, edgelist= [(1,0)], width = 1, alpha = 1)
nx.draw_networkx_edges(F, post, edgelist= [(0,2)], width = 1, alpha = 1)
nx.draw_networkx_edges(F, post, edgelist= [(2,1)], width = 1, alpha = 1)
plt.axis('off')
plt.show()

And I have so far found no way to change the colour according to the direction of the edge. Ideally, I would like to achieve something like this:

Please see photo here

CodePudding user response:

This isn't implemented in networkx, but it would be possible in matplotlib, albeit involve a substantial amount of computation, depending on what exactly you would like to do:

If you want to plot your edges as simple lines, you could precompute the node layout, and then follow this guide to plot multicolored lines between the node positions using matplotlib's LineCollection.

If you wanted to draw arrows, you would have to a) compute the path of the corresponding FancyArrowPatch, and then b) use that path to clip an appropriately oriented color-gradient mesh. For a simple triangle, this is demonstrated here.

  • Related