在视觉上漂亮的树状结构中绘制有向网络图

Plot directed network graph in visually beautiful tree structure

提问人:Slybot 提问时间:11/16/2023 最后编辑:Slybot 更新时间:11/16/2023 访问量:37

问:

给定 Networkx 包中的有向网络,我想创建一个漂亮的树形图,其中图层和有向边在视觉上具有吸引力和连贯性。由于某种原因,我无法使用 Graphviz,我需要 networkx 和 matplotlib 解决方案。

举个例子,下面的代码生成分层树和有向网络,但有向边交叉,看起来不像一个好的树结构。

import networkx as nx
import matplotlib.pyplot as plt

# Parameters
tree = [[0], [2], [1], [4], [5], [3], [6], [8, 9], [7], [13, 11], [15], [12, 16], [10, 14, 17]]
localDominatorDict = {0: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17],
                      1: [3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 14, 15, 16, 17],
                      2: [1, 3, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17],
                      3: [6, 7, 8, 9, 14, 16, 17], 
                      4: [5, 8, 9, 13, 15, 16, 17],
                      5: [3, 6, 8, 9, 10, 11, 12, 13, 15, 16, 17],
                      6: [9, 10, 13, 14],
                      7: [11, 16, 17],
                      8: [7, 11, 16],
                      9: [7, 11, 12, 15, 17],
                      10: [],
                      11: [12, 14, 15, 16, 17],
                      12: [17],
                      13: [14, 15],
                      14: [],
                      15: [16, 17],
                      16: [14, 17],
                      17: []}

# Create DiGraph
G = nx.DiGraph()

# Add nodes
for idx, layer in enumerate(tree):
    for node in layer:
        G.add_node(node, layer=idx)

# Add edges
for idx, layer in enumerate(tree[::-1]):
    if idx < len(tree) - 1:
        for node in layer:
            flag = True
            increment = 1
            while flag:
                for upperNode in tree[::-1][idx + increment]:
                    if node in localDominatorDict[upperNode]:
                        G.add_edge(upperNode, node)
                        flag = False
                increment += 1

# Positioning nodes based on layers
pos = {}
for i, layer in enumerate(tree):
    for j, node in enumerate(layer):
        pos[node] = (j - len(layer) / 2, -i)

# Plotting the graph
plt.figure(figsize=(8, 6))
nx.draw(G, pos, with_labels=True, node_size=500, node_color='lightblue', font_weight='bold', arrows=True)
plt.title('Directed Graph with Layers')
plt.show()

Directed network

python matplotlib networkx

评论

2赞 warped 11/17/2023
您的图形也不是一棵树。

答: 暂无答案