简体   繁体   English

使用默认为节点名称的节点标签绘制networkx图

[英]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. NetworkX功能强大,但我试图绘制一个默认情况下显示节点标签的图形,令我感到惊讶的是,对于看似不是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 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)在图形中内联显示默认标签(在这种情况下为Node1,Node2)?

tl/dr: just add with_labels=True to the nx.draw call. tl / dr:只需将with_labels=True添加到nx.draw调用即可。

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. 如果您想做一些事情以使节点标签不同,则可以发送dict作为参数。 So for example, 例如

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

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

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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