【问题标题】:Can I horizontally align a pydot graph by distance from head?我可以按距头部的距离水平对齐 pydot 图吗?
【发布时间】:2021-05-16 14:46:55
【问题描述】:

我创建了一个如下图所示的图表。但是,我想按与头部 (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)

【问题讨论】:

    标签: python networkx graphviz pydot


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-12-16
      • 2011-04-20
      • 2012-08-27
      • 1970-01-01
      • 2020-06-24
      • 1970-01-01
      • 2015-09-17
      相关资源
      最近更新 更多