在节点外部标记networkx节点属性
问题描述:
我正在研究一个属于两种类型的小例子节点集{'human', 'machine'}
,我想在字典形式中标记节点属性,在networkx
图中的每个节点之外,如节点c, e,j在下面的图表中。 (我使用的MS Word添加图表上的字典类型属性):使用下面的代码生成在节点外部标记networkx节点属性
基部情节:
import networkx as nx
G = nx.Graph()
G.add_nodes_from(['a', 'b', 'c', 'd', 'e', 'f', 'g'], type = 'machine')
G.add_nodes_from(['h', 'i', 'j'], type = 'human')
G.add_edges_from([('a', 'c'), ('a', 'b'), ('a', 'd'), ('a', 'f'), ('b', 'd'), ('b', 'e'), ('b', 'g'), ('c', 'f'), ('c', 'd'), ('d', 'f'), ('d', 'e'), ('d', 'g'), ('e', 'g'), ('f', 'g'), ('f', 'h'), ('g', 'h'), ('h', 'i'), ('i', 'j')])
def plot_graph(G, weight_name=None):
import matplotlib.pyplot as plt
plt.figure()
pos = nx.spring_layout(G)
edges = G.edges()
weights = None
if weight_name:
weights = [int(G[u][v][weight_name]) for u,v in edges]
labels = nx.get_edge_attributes(G,weight_name)
nx.draw_networkx_edge_labels(G,pos,edge_labels=labels)
nx.draw_networkx(G, pos, edges=edges, width=weights);
else:
nx.draw_networkx(G, pos, edges=edges);
plot_graph(G, weight_name=None)
plt.savefig('example.png')
plt.show()
但这里的问题是,
nx.get_node_attributes()
和nx.draw_networkx_labels()
函数不会在标签上包含字典关键字(在本例中为'type')(这只适用于nx.get_edge_attributes()和nx.draw_networkx_edge_labels()),如果一个w应该使用nx.get_node_attributes()
和nx.draw_networkx_labels()
,原始节点名称将被属性值替换。
我想知道是否有其他方法来标记字典格式属性在每个节点以外的字典格式,同时保持节点名称内的节点?我应该如何修改我当前的代码?
答
不包括键的nx.draw_networkx_labels()
的问题可以通过创建一个新的字典来解决,该字典会将表示整个字典的字符串保存为值。
node_attrs = nx.get_node_attributes(G, 'type')
custom_node_attrs = {}
for node, attr in node_attrs.items():
custom_node_attrs[node] = "{'type': '" + attr + "'}"
关于绘图节点的名称和属性,则可以使用nx.draw()
正常绘制节点名称,然后nx.draw_networkx_labels()
绘制属性 - 这里可以手动换挡属性位置高于或低于节点。在pos
下面的块中保存节点位置,并且pos_attrs
保存放置在适当节点上方的属性位置。
pos_nodes = nx.spring_layout(G)
pos_attrs = {}
for node, coords in pos_nodes.items():
pos_attrs[node] = (coords[0], coords[1] + 0.08)
完整的示例:
import networkx as nx
import matplotlib.pyplot as plt
G = nx.Graph()
G.add_nodes_from(['a', 'b', 'c', 'd', 'e', 'f', 'g'], type = 'machine')
G.add_nodes_from(['h', 'i', 'j'], type = 'human')
G.add_edges_from([('a', 'c'), ('a', 'b'), ('a', 'd'), ('a', 'f'), ('b', 'd'), ('b', 'e'), ('b', 'g'), ('c', 'f'), ('c', 'd'), ('d', 'f'), ('d', 'e'), ('d', 'g'), ('e', 'g'), ('f', 'g'), ('f', 'h'), ('g', 'h'), ('h', 'i'), ('i', 'j')])
plt.figure()
pos_nodes = nx.spring_layout(G)
nx.draw(G, pos_nodes, with_labels=True)
pos_attrs = {}
for node, coords in pos_nodes.items():
pos_attrs[node] = (coords[0], coords[1] + 0.08)
node_attrs = nx.get_node_attributes(G, 'type')
custom_node_attrs = {}
for node, attr in node_attrs.items():
custom_node_attrs[node] = "{'type': '" + attr + "'}"
nx.draw_networkx_labels(G, pos_attrs, labels=custom_node_attrs)
plt.show()
输出:
最后提示:如果你有很多的边缘和您的节点属性难以阅读,你可以尝试将边缘的颜色设置为较浅的灰色阴影。
非常感谢您澄清这一点,您的答案有助于解决我的问题! –