我可以按距头部的距离水平对齐 pydot 图吗?

Can I horizontally align a pydot graph by distance from head?

我创建了一个图表,如下所示。但是,我想按距头部 (A) 的最短距离分层排列图形。换句话说:C、B、D、E 应该都在同一层级并且水平对齐,因为它们都离 A 有 1 个边(最短路径)。然后,F、G、H 应该在下一个水平,因为它们各有 2 个边缘,等等

我喜欢图表的外观,因此解决方案最好保持这种可视化风格。

import matplotlib.pyplot as plt
import networkx as nx
import pydot
from networkx.drawing.nx_pydot import graphviz_layout
from IPython.display import Image, display

G=nx.Graph()
G.add_edges_from([
    ('A','B'),
    ('A','C'),
    ('A','E'),
    ('A','D'),
    ('B','C'),
    ('B','F'),
    ('C','F'),
    ('D','H'),
    ('D','G'),
    ('E','H'),
    ('F','I'),
    ('G','I'),
    ('G','J'),
    ('H','J'),
    ('I','K'),
    ('J','K')
])


pdot = nx.drawing.nx_pydot.to_pydot(G)
graph = Image(pdot.create_png())
display(graph)

有一个内置函数可以计算到给定节点的最短路径的长度。长度可用于指定一个坐标。 另一个坐标是根据与A:

距离相同的节点数计算的
from collections import Counter

distances = list(nx.single_target_shortest_path_length(G, 'A'))

counts = Counter(a[1] for a in distances)

for c in counts:
    counts[c] /= 2 # divide by 2 to get symmetrical distances from the y-axis

# generate dictionary that holds node positions:
pos = {}
for (node, d) in distances:
    pos[node] = (counts[d], -d) # x-position determined by number of counts, y position determined by distance. 
    counts[d] -= 1 # decrement count to draw nodes at shifted position
    
nx.draw_networkx(G, pos=pos) # i dont have pydot, but the basic logic should work. just use the pos argument in the pydot function.