使用默认为节点名称的节点标签绘制networkx图
NetworkX功能强大,但是我试图绘制一个默认情况下显示节点标签的图形,令我感到惊讶的是,对于看似不熟悉Networkx的人来说,这看似简单的任务是多么繁琐.有一个示例显示了如何在图上添加标签.
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?
有没有办法让nx.draw(G)
在图表中内联显示默认标签(在这种情况下为Node1,Node2)?
Is there a way to make nx.draw(G)
show the default labels (Node1, Node2 in this case) inline in the graph?
tl/dr:只需将with_labels=True
添加到nx.draw
调用中即可.
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')
如果您想做一些事情以使节点标签不同,则可以发送dict作为参数.例如,
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)