Sourav Dutta
Sourav Dutta

Reputation: 11

Preventing Overlap of edges and nodes with NetwrokX/Matplotlib

I am trying to plot numbers of a problem "Collatz Conjecture" which forms a nice network between numbers(node labels). However, in the final plot of the solution using networkx nx.spring_layout(G) I get overlapping edges and nodes: enter image description here enter image description here

The nx.spring_layout is configured(through trial and error) as:

 pos=nx.spring_layout(G,k = 0.004, iterations = 500, scale = 0.6)
 nx.draw(G, labels=labels, pos=pos, font_size = 6, alpha = 0.5, node_size = nodes.values())
 plt.show()

Is there a particular way to prevent this overlap, given that there is adequate empty space in the plotting window? Node size in this case is dictated by the value of:len(G.neighbors(node)) No node has more that 3 neighbours and the max node size is capped at 300 to further prevent overlap. The odd thing is that for the longer branches this seems to be handled fairly well, but for branches such as [24,12,6,3,10] as in the images, it fails to demarcate this branch sufficiently, in other cases it overlaps altogether. Please advise if I should use another layout besides nx.spring_layout(G) which might handle this better.

Upvotes: 1

Views: 4660

Answers (1)

Chris
Chris

Reputation: 161

Picking up on the really helpful comment from DYZ about using graphviz_layout(), I thought I'd share my experience here, in case anyone else is having a similar issue, because getting this set up wasn't totally straightforward (for me, at least, on Ubuntu 16.04):

I found sudo pip install pygraphviz didn't work, because it couldn't find one of the files it needed. I then tried sudo apt-get install graphviz libgraphviz-dev pkg-config followed by sudo pip install pygraphviz (thanks to this suggestion), which looked like it worked (i.e. installation succeeded), but I still couldn't use graphviz_layout() through NetworkX. So, I uninstalled pygraphviz (sudo pip uninstall pygraphviz) and installed it again as follows (thanks to a tip on this thread):

sudo pip install pygraphviz --install-option="--include-path=/usr/include/graphviz" --install-option="--library-path=/usr/lib/graphviz/"

This did work, and visualisations with graphviz_layout() do seem to have less node overlap than using NetworkX's spring_layout(), as well as a more æsthetically pleasing approach to edge length and cluster spacing.

Upvotes: 1

Related Questions