繁体   English   中英

Networkx节点标签顺序错误

[英]Networkx node labels are in wrong order

我用Python编写了绘制图形的代码。 输入看起来像这样:

  1. 顶点数。
  2. 顶点的第一坐标。
  3. 相同顶点顶点的第二坐标。
  4. 如果有多个顶点,请重复(2)和(3)。 每个数字必须在换行符上。

图形已正确绘制,但每个节点上的标签均错误。

输入示例:

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.

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