2

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

2 Answers 2

5

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

enter image description here

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

Sign up to request clarification or add additional context in comments.

6 Comments

That's cool, Joel!! When I saved the image to a file, using this line you provided (plt.savefig('tmp.png')), the label appears. I'm also using mac, and don't know why "plt.show()" can't call out the labels.
I tried to "accept" or "like" your answer, but it seems I can't do it because I don't have enough reputation. How should I accept your answer?
The problem for why plt.show() isn't working is to do with a (known) bug in matplotlib. I'm not sure if they've fixed it in newer versions or not. By the way - you can also save as .pdf or several other formats just by using the appropriate extension like plt.savefig('name.pdf')
You can't vote answers up until you have higher reputation, but there should be a checkmark at about the same place as the up/down arrows where you can click to accept.
Ah yes!! I found that! : )
|
3

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:

enter image description here

with_labels is by default True so not necessary to specify

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.