3
votes

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.

code

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()

image

[1] http://imgur.com/PIvEm3y

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!

2

2 Answers

2
votes

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):

spring-layout

Maybe a networkx.draw_circular layout would be a better fit:

nx.draw_circular(g)

circular-layout

You can read about all the NetworkX layouts here, including Graphviz (as suggested by @ThomasHobohm).

1
votes

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.