[英]Networkx: Replacing labels of nodes
我有以下最少的代碼:
import networkx as nx
import matplotlib.pyplot as plt
G = nx.DiGraph()
#G = nx.Graph()
#G = nx.path_graph(4)
pos1 = {0: (0, 0), 1: (2, 1), 2: (2, 0), 3: (2,-1)}
G.add_edge(0, 1)
G.add_edge(0, 3)
G.add_edge(1, 2)
G.add_edge(2, 3)
# First Network
plt.figure(0)
nx.draw_networkx(G, pos1) # Puts numbers as labels of nodes
plt.axis("off")
plt.savefig('graph1.png')
# Second network
plt.figure(1)
mapping = {0: "Zero", 1: "One", 2: "Two", 3: "Three"}
H = nx.relabel_nodes(G, mapping)
nx.draw_networkx(H) # Works
''' The below line I want to modify '''
#nx.draw_networkx(H, pos1) # Doesn't work
# Says: NetworkXError: Node 'Zero' has no position
plt.axis("off")
plt.savefig('graph2.png')
plt.show()
在這里,我試圖替換新圖H
中的 label 名稱。 但它顯示錯誤,因為我正在使用節點坐標。
現在的輸出是:
第二張圖需要修正。 此外,節點的大小是否可以自動調整,奇數編號(first.network 的標簽)節點的顏色是否不同?
附言。 如果networkx
有限制,那么使用其他模塊的示例也可以達到目的。
最簡單的方法是使用新的節點名稱創建一個重新標記的pos
字典:
pos1 = {0: (0, 0), 1: (2, 1), 2: (2, 0), 3: (2,-1)}
mapping = {0: "Zero", 1: "One", 2: "Two", 3: "Three"}
pos_new = {mapping[k]: v for k, v in pos1.items()}
# use the above with nx.draw_networkx(H, pos_new)
我認為解決這個問題的最好方法是不使用nx.draw.networkx
命令,而是使用單獨的標簽、節點和邊繪制命令。 使用nx.draw.networkx_labels
您可以直接傳遞字典而無需更改節點名稱:
import networkx as nx
import matplotlib.pyplot as plt
G = nx.DiGraph()
pos1 = {0: (0, 0), 1: (2, 1), 2: (2, 0), 3: (2,-1)}
G.add_edge(0, 1)
G.add_edge(0, 3)
G.add_edge(1, 2)
G.add_edge(2, 3)
node_colors = ['red'if i%2==0 else 'blue' for i in G.nodes]
mapping = {0: "Zero", 1: "One", 2: "Two", 3: "Three"}
plt.figure()
nx.draw_networkx_nodes(G, pos=pos1,node_color=node_colors, node_size=500)
nx.draw_networkx_edges(G, pos=pos1)
nx.draw_networkx_labels(G, pos=pos1, labels=mapping)
plt.axis("off")
plt.show()
這會產生:
如果要使節點大小適合標簽,請對其進行操作。 如果你只關心文本,而不關心節點本身。 不要使用nx.draw.networkx_nodes
命令,而是將bbox
參數添加到nx.draw.networkx_labels
。 像這樣:
plt.figure()
#nx.draw_networkx_nodes(G, pos=pos1,node_color=node_colors, node_size=500)
nx.draw_networkx_edges(G, pos=pos1)
nx.draw_networkx_labels(G, pos=pos1, labels=mapping, bbox ={})
plt.axis("off")
plt.show()
哪個產生:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.