1 回答

TA貢獻(xiàn)2036條經(jīng)驗(yàn) 獲得超8個(gè)贊
drawnetworkx的各種函數(shù)都帶有一個(gè)pos參數(shù),該參數(shù)是一個(gè)字典,其中節(jié)點(diǎn)名稱為鍵,x,y 坐標(biāo)為值。
你可以自己生成這個(gè)。如果您知道要強(qiáng)加的層次結(jié)構(gòu),則可以將層次結(jié)構(gòu)轉(zhuǎn)換為 y 位置,然后隨時(shí)添加填充 x 位置:
# exctracting nodes from dictionary into list:
nodes = [{'id': 'build'}, {'id': 'root'}, {'id': 'utils'}, {'id': 'codegen'}, {'id': 'codegen.templates'}, {'id': 'nodes.shapes'}, {'id': 'codegen.c_types'}, {'id': 'nodes'}, {'id': 'containers'}, {'id': 'distutils'}, {'id': 'wheel'}, {'id': 'tools.testing'}, {'id': 'finalizations'}, {'id': 'importing'}, {'id': 'plugins'}, {'id': 'freezer'}, {'id': 'tree'}, {'id': 'specs'}, {'id': 'optimizations'}, {'id': 'plugins.standard'}, {'id': 'tools.general.dll_report'}, {'id': 'tools.specialize'}, {'id': 'tools.testing.compare_with_cpython'}, {'id': 'tools.testing.find_sxs_modules'}, {'id': 'tools.testing.measure_construct_performance'}, {'id': 'tools.testing.run_root_tests'}, {'id': 'tools'}]
nodelist = []
for n in nodes:
for k, v in n.items():
nodelist.append(v)
# hierarchy here is arbitrarily defined based on the index of hte node in nodelist.
# {hierarchy_level : number_of_nodes_at_that_level}
hierarchy = {
0:4,
1:10,
2:5,
3:5,
4:3
}
coords = []
for y, v in hierarchy.items():
coords += [[x, y] for x in list(range(v))]
# map node names to positions
# this is based on index of node in nodelist.
# can and should be tailored to your actual hierarchy
positions = {}
for n, c in zip(nodelist, coords):
positions[n] = c
fig = plt.figure(figsize=(15,5))
nx.draw_networkx_nodes(G, pos=positions, node_size=50)
nx.draw_networkx_edges(G, pos=positions, alpha=0.2)
# generate y-offset for the labels, s.t. they don't lie on the nodes
label_positions = {k:[v0, v1-.25] for k, (v0,v1) in positions.items()}
nx.draw_networkx_labels(G, pos=label_positions, font_size=8)
plt.show()
節(jié)點(diǎn)標(biāo)簽有些重疊,但這可以通過字體大小進(jìn)行調(diào)整,通過圖形尺寸進(jìn)行額外偏移
編輯:
旋轉(zhuǎn)節(jié)點(diǎn)標(biāo)簽以避免文本重疊:
text = nx.draw_networkx_labels(G, pos=label_positions, font_size=8)
for _, t in text.items():
t.set_rotation(20)
添加回答
舉報(bào)