网络图中如何在节点之外标记网络节点属性

7
我正在处理一个小的节点集示例,它属于两种类型{'human', 'machine'},我想在每个节点之外以字典形式标记节点属性,就像下面图表中的节点c、e、j所示。 (我使用MS Word在图表上添加了字典类型的属性。):

enter image description here

使用以下代码生成基本绘图:

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()有效)。我想知道是否有其他方法可以在每个节点外部以字典格式标记属性,同时保持节点名称在节点内部?我应该如何修改当前的代码?

1个回答

21

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()

输出:

在此输入图片描述

最后一个提示:如果您有很多边缘并且节点属性难以阅读,您可以尝试将边缘的颜色设置为浅灰色。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接