我可以通过与头部的距离水平对齐pydot图形吗?

2024-09-30 23:35:27 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

enter image description here

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)

Tags: fromimageimportnetworkx图形距离asdisplay
1条回答
网友
1楼 · 发布于 2024-09-30 23:35:27

有一个内置函数,允许计算到给定节点的最短路径的长度。长度可用于指定一个坐标。 另一个坐标是根据与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. 

enter image description here

相关问题 更多 >