Python 使用 networkx 的节点标签
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15548506/
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
Node labels using networkx
提问by Maoritzio
I'm creating a graph out of given sequence of Y values held by curveSeq. (the X values are enumerated automatically: 0,1,2...)
我正在根据给定的 Y 值序列创建一个图表curveSeq。(X 值会自动枚举:0,1,2...)
i.e for curveSeq = [10,20,30], my graph will contain the points:
即对于curveSeq = [10,20,30],我的图表将包含点:
<0,10>, <1,20>, <2,30>.
I'm drawing a series of graphs on the same nx.Graphin order to present everything in one picture.
我正在同一张图上绘制一系列图表nx.Graph,以便在一张图片中展示所有内容。
My problem is:
我的问题是:
- Each node presents its location. i.e the node in location
<0,10>presents its respective label and I don't know how to remove it. - There are specific nodes that I want to add a label to, but I don't know how.
- 每个节点显示其位置。即位置中的节点
<0,10>显示其各自的标签,我不知道如何删除它。 - 我想向某些特定节点添加标签,但我不知道如何添加。
for example, for the sequence:
例如,对于序列:
[0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1,1]
The received graph is:
收到的图是:


The code is:
代码是:
for point in curveSeq:
cur_point = point
#assert len(cur_point) == 2
if prev_point is not None:
# Calculate the distance between the nodes with the Pythagorean
# theorem
b = cur_point[1] - prev_point[1]
c = cur_point[0] - prev_point[0]
a = math.sqrt(b ** 2 + c ** 2)
G.add_edge(cur_point, prev_point, weight=a)
G.add_node(cur_point)
pos[cur_point] = cur_point
prev_point = cur_point
#key:
G.add_node((curve+1,-1))
pos[(curve+1,-1)] = (curve+1,-1)
nx.draw(G, pos=pos, node_color = colors[curve],node_size=80)
nx.draw_networkx_edges(G,pos=pos,alpha=0.5,width=8,edge_color=colors[curve])
plt.savefig(currIteration+'.png')
采纳答案by Aric
You can add the with_labels=Falsekeyword to suppress drawing of the labels with networkx.draw(), e.g.
您可以添加with_labels=False关键字以禁止绘制标签networkx.draw(),例如
networkx.draw(G, pos=pos, node_color=colors[curve],
node_size=80, with_labels=False)
Then draw specific labels with
然后绘制特定的标签
networkx.draw_networkx_labels(G,pos, labels)
where labels is a dictionary mapping node ids to labels.
其中,labels 是将节点 id 映射到标签的字典。
Take a look at this example http://networkx.github.com/documentation/latest/examples/drawing/labels_and_colors.html
看看这个例子http://networkx.github.com/documentation/latest/examples/drawing/labels_and_colors.html

