I am testing out how to create network graphs on "networkx"; my problem is that when I try plotting these graphs using "matplotlib", the nodes, edges, and labels appear jumbled. I want to have the labels attached to right node, and I want the edges to look like they are connecting the nodes.
import networkx as nx
try:
import matplotlib.pyplot as plt
except:
raise
g = nx.MultiGraph()
strList = ["rick james", "will smith", "steve miller", "rackem willie", "little tunechi", "ben franklin"]
strList2 = ["jules caesar", "atticus finch", "al capone", "abe lincoln", "walt white", "doc seuss"]
i = 0
while i < len(strList) :
g.add_edge(strList[i], strList2[i])
i = i + 1
nx.draw_networkx_nodes(g,pos = nx.spring_layout(g), nodelist = g.nodes())
nx.draw_networkx_edges(g,pos = nx.spring_layout(g), edgelist = g.edges())
nx.draw_networkx_labels(g,pos=nx.spring_layout(g))
#plt.savefig("testImage.png")
plt.show()
[1] https://i.sstatic.net/Y2Xi6.jpg
I want my connections to be like this:
rick james <--> jules caesar
will smith <--> atticus finch
steve miller <--> al capone
...etc
Any help/insight is greatly appreciated!
The spring layout is stochastic (random). One issue you're having comes from the fact that you are running this stochastic process a different time -- producing a different layout -- for the nodes, edges, and labels. Try this, where you compute the layout a single time:
pos = nx.spring_layout(g)
nx.draw_networkx_nodes(g, pos=pos, nodelist = g.nodes())
nx.draw_networkx_edges(g, pos=pos, edgelist = g.edges())
nx.draw_networkx_labels(g, pos=pos)
Or in the case that you don't need to style individual nodes/edges/labels:
nx.draw_spring(g)
I won't claim that this will give you a "good" layout because it doesn't (at least on my machine):

Maybe a networkx.draw_circular layout would be a better fit:
nx.draw_circular(g)

You can read about all the NetworkX layouts here, including Graphviz (as suggested by @ThomasHobohm).
Matplotlib is very bad at drawing readable graphs. I suggest you use Graphviz, at it's supported by NetworkX out of the box, and it let's you toggle way more settings with the dot format.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With