[英]Networkx node labels are in wrong order
我用Python编写了绘制图形的代码。 输入看起来像这样:
图形已正确绘制,但每个节点上的标签均错误。
输入示例:
10
1
3
3
4
1
2
4
2
3
2
2
6
2
5
6
7
5
8
7
8
4
请在每个数字的换行符上输入输入!!!
输出示例:
我的输出(错了):
我的代码:
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
#f=open("output.txt","r+")
G=nx.Graph()
#ed=input("How many edges?")
ver=int(input("How many vertices?"))
for z in range(0, ver):
x = int(input())
y = int(input())
G.add_edge(x,y)
labelmap = dict(zip(G.nodes(), ["1", "2", "3", "4","5","6","7","8"]))
nx.draw(G, labels=labelmap, with_labels=True)
plt.show()
#, labels=labelmap, with_labels=True
节点在首次引用时由networkx
自动添加。 如果从C-> B然后是F-> A绘制一条边,则将按照该顺序创建节点(C,B,F,A)。 但是,您的labelmap
假定它们按数字顺序排列。
如果仅使用以下命令,则将在节点上正确打印节点标签:
nx.draw(G, with_labels=True)
或者,您可以在添加节点以存储订单时跟踪它们,例如
nodes = []
for z in range(0, ver):
x = int(input())
y = int(input())
G.add_edge(x,y)
if x not in nodes:
nodes.append(x)
if y not in nodes:
nodes.append(y)
labelmap = dict(zip(nodes, nodes))
如果需要,您也可以使用这种方法格式化/更改标签。
正如我在评论中所说, networkx
中的标签是自动分配的:
import networkx as nx
from string import ascii_uppercase
G = nx.Graph()
edges = list(zip(ascii_uppercase, ascii_uppercase[1:]))
print(edges)
for i, j in edges:
G.add_edge(i, j)
# jupyter notebook
%matplotlib inline
nx.draw(G, with_labels=True)
[('A', 'B'), ('B', 'C'), ('C', 'D'), ('D', 'E'), ('E', 'F'), ('F', 'G'), ('G', 'H'), ('H', 'I'), ('I', 'J'), ('J', 'K'), ('K', 'L'), ('L', 'M'), ('M', 'N'), ('N', 'O'), ('O', 'P'), ('P', 'Q'), ('Q', 'R'), ('R', 'S'), ('S', 'T'), ('T', 'U'), ('U', 'V'), ('V', 'W'), ('W', 'X'), ('X', 'Y'), ('Y', 'Z')]
默认情况下, networkx
节点/顶点具有整数作为标签:
G = nx.path_graph(15)
print(G.edges())
%matplotlib inline
nx.draw(G, with_labels=True)
[(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7), (7, 8), (8, 9), (9, 10), (10, 11), (11, 12), (12, 13), (13, 14)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.