[英]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.