简体   繁体   中英

How can I display label for graph nodes in python networkx

I have following code to visualize networkx graph:

node_positions = networkx.spring_layout(graph)
networkx.draw_networkx_nodes(graph, node_positions)
networkx.draw_networkx_edges(graph, node_positions, style='dashed')

I want to display node label on each node. graph.nodes() will give me list of all the nodes but how can I use them to label nodes on the graph?

I tried this, but it is not working:

networkx.draw_networkx_labels(graph,node_positions,graph.nodes(data="false"),font_size=16)

EDIT:

I tried following and its working for now:

for node,_ in graph.nodes(data="False"):
        labels[node] = node;
networkx.draw_networkx_labels(graph,node_positions,labels,font_size=16)

If there is still some elegant way to do it please let me know. I feel creating new dict is overkill, redundant and should not be required.

在此处输入图片说明 Check nx.draw source code or drawing documentation . I am not quite sure I got your question correctly because according to my understanding it is a fairly straight forward issue, simply you are allowed to add labels for a graph as follows:

networkx.draw(graph, node_positions, with_labels = True)

You can also, use draw_spring directly without having to explicity assign node positions:

networkx.draw_spring(graph, with_labels = True)

The figure shows the result of running the following code:

import networkx as nx
G = nx.erdos_renyi_graph(10,0.4)
nx.draw(G, with_labels=True)
plt.show()

Your problem is that you sent the list of graph nodes in place of an optional argument where it expected a dict. By having this optional argument, networkx allows you to have whatever label you want appear. In your case you want the obvious label of just the node's name. This is the default behavior. So simply

networkx.draw_networkx_labels(graph,node_positions,font_size=16)

will suffice. Don't send the dict and it will use the node names to label them.

An alternate option is to do exactly what abdallah suggested, and draw the entire graph in one networkx.draw command with the with_labels=True option.


brief comment on format of your question

When I initially read your question, I assumed the draw_networkx_labels command was giving an output different from what you expected.

Now that I've tried your code, I see it actually gives an error. Telling us that and that the error is

AttributeError: 'list' object has no attribute 'items'

would have made it much easier to figure out what was wrong, so for future reference if you get an error message, it contains information about what the problem is. If you post a question, post the error message as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM