Reputation: 123
I'm using Python to conduct social network analysis, very simple kind, and as a newbie (to both SNA and Python).
When drawing a graph using Terminal on my mac, I've tried every method I can but still can only draw nodes and edges, but no label of nodes in or beside them.
What scripts should I use to make the labels visible?
>>> import networkx as nx
>>> import networkx.generators.small as gs
>>> import matplotlib.pyplot as plt
>>> g = gs.krackhardt_kite_graph()
>>> nx.draw(g)
>>> plt.show()
Upvotes: 2
Views: 4968
Reputation: 23887
EdChum gave a good answer. Another option which will by default not show the axes and produces a graph that takes up slightly more of the figure is to use nx.draw
but give it the argument with_labels = True
. (for nx.draw
, you need to set with_labels
to True
, but for nx.draw_networkx
it defaults to True
).
import networkx as nx
import networkx.generators.small as gs
import matplotlib.pyplot as plt
g = gs.krackhardt_kite_graph()
nx.draw(g,with_labels=True)
plt.savefig('tmp.png')
Be aware that there is a bug such that sometimes plt.show() will not show the labels. From what I've been able to tell, it's not in networkx, but rather has something to do with the rendering. It saves fine, so I haven't worried about following up on it in detail. It shows up for me using ipython on a macbook. Not sure what other systems it's on. More detail at pylab/networkx; no node labels displayed after update
Upvotes: 5
Reputation: 394319
Try using draw_networkx
:
import networkx as nx
import networkx.generators.small as gs
import matplotlib.pyplot as plt
g = gs.krackhardt_kite_graph()
nx.draw_networkx(g)
plt.show()
This results in:
with_labels
is by default True
so not necessary to specify
Upvotes: 3