慕桂英3389331
drawnetworkx的各种函数都带有一个pos参数,该参数是一个字典,其中节点名称为键,x,y 坐标为值。你可以自己生成这个。如果您知道要强加的层次结构,则可以将层次结构转换为 y 位置,然后随时添加填充 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] = cfig = 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 nodeslabel_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()节点标签有些重叠,但这可以通过字体大小进行调整,通过图形尺寸进行额外偏移编辑:旋转节点标签以避免文本重叠:text = nx.draw_networkx_labels(G, pos=label_positions, font_size=8)for _, t in text.items(): t.set_rotation(20)