0

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

1 Answers1

0

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.

Paul Brodersen
  • 11,221
  • 21
  • 38
  • Thanks so much for confirming this can't be done in networkx - though it would be lovely if it were possible. The first solution you gave is pretty good but I'm still not sure how we would go about assigning the start of a line (edge) with one colour and the end of it with another colour. I could do it manually but my network has over 200 lines. Some object like index() in R would have been perfect. – Academic005 Feb 23 '22 at 01:27
  • You can make your own custom colormap/gradient using `cmap = LinearSegmentedColormap.from_list('my_name', ['start_color', 'end_color'])`, as discussed [here](https://matplotlib.org/stable/tutorials/colors/colormap-manipulation.html#directly-creating-a-segmented-colormap-from-a-list). – Paul Brodersen Feb 23 '22 at 09:43
  • Hi, I tried it, but it creates a colormap instead i.e. a all the edge are different colours but each edge is one solid colour and not a gradient. Do you know what code I should include so that each edge is a gradient (and that all of them are the same gradient)? – Academic005 Feb 24 '22 at 02:38
  • It would be helpful if you amended your question to include the latest version of your code. – Paul Brodersen Feb 24 '22 at 18:22
  • That is the latest version of my code - I just haven't added the 'import networkx as nx' and 'F = NxDiGraph()' lines – Academic005 Feb 26 '22 at 01:31