Python 使用默认为节点名称的节点标签绘制 networkx 图
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28533111/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Plotting networkx graph with node labels defaulting to node name
提问by Pranjal Mittal
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.
NetworkX 很强大,但我试图绘制一个默认显示节点标签的图表,我很惊讶这个看似简单的任务对于 Networkx 的新手来说是多么乏味。有一个示例显示了如何向绘图添加标签。
https://networkx.github.io/documentation/latest/examples/drawing/labels_and_colors.html
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?
有没有办法nx.draw(G)
在图表中内联显示默认标签(在这种情况下为节点 1,节点 2)?
采纳答案by Joel
tl/dr: just add with_labels=True
to the nx.draw
call.
tl/dr:只需添加with_labels=True
到nx.draw
通话中即可。
The pageyou 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,
如果您想做某事以使节点标签不同,您可以发送一个 dict 作为参数。例如,
labeldict = {}
labeldict["Node1"] = "shopkeeper"
labeldict["Node2"] = "angry man with parrot"
nx.draw(G, labels=labeldict, with_labels = True)