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