的问题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()
Output:
最后提示:如果您有很多边并且节点属性难以阅读,您可以尝试将边的颜色设置为较浅的灰色。