简体   繁体   中英

Plotting networkx graph with node labels defaulting to node name

NetworkX is powerful but I was trying to plot a graph which shows node labels by default and I was surprised how tedious this seemingly simple task could be for someone new to Networkx. There is an example which shows how to add labels to the plot.

https://networkx.github.io/documentation/latest/examples/drawing/labels_and_colors.html

The problem with this example is that it uses too many steps and methods when all I want to do is just show labels which are same as the node name while drawing the graph.

# Add nodes and edges
G.add_node("Node1")
G.add_node("Node2")
G.add_edge("Node1", "Node2")
nx.draw(G)    # Doesn't draw labels. How to make it show labels Node1, Node2 along?

Is there a way to make nx.draw(G) show the default labels (Node1, Node2 in this case) inline in the graph?

tl/dr: just add with_labels=True to the nx.draw call.

The page you were looking at is somewhat complex because it shows how to set lots of different things as the labels, how to give different nodes different colors, and how to provide carefully control node positions. So there's a lot going on.

However, it appears you just want each node to use its own name, and you're happy with the default color and default position. So

import networkx as nx
import pylab as plt

G=nx.Graph()
# Add nodes and edges
G.add_edge("Node1", "Node2")
nx.draw(G, with_labels = True)
plt.savefig('labels.png')

在此处输入图片说明

If you wanted to do something so that the node labels were different you could send a dict as an argument. So for example,

labeldict = {}
labeldict["Node1"] = "shopkeeper"
labeldict["Node2"] = "angry man with parrot"

nx.draw(G, labels=labeldict, with_labels = True)

在此处输入图片说明

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