python在SPYDER中绘制有向图

use*_*622 5 python networkx

我正在使用SPYDER.我有以下代码.代码生成图形.但图表不干净.我想在图中看到图层 - 我的第一层有'开始'节点,第二层有1,2,3节点,第三层有'a','b','c'节点,最后一层有'结束'节点.任何想法我怎么能实现我的目标?

import networkx as nx
import matplotlib.pyplot as plt
import os.path as path

G=nx.DiGraph()
G.add_nodes_from(['start',1,2,3,'a','b','c','end'])

G.nodes(data=True)

G.add_edge('start',2)
G.add_edge('start',3)
G.add_edge(2,'b')
G.add_edge('b','end')
G.add_edge('a','end')
G.add_edge('f','g')
nx.draw(G)
Run Code Online (Sandbox Code Playgroud)

------------------------更新------------------

逐层我的意思是我应该看到附图中的网络.我希望以这种方式绘制网络,因为层X中的节点将直接连接到层X + 1或层X-1中的节点

在此输入图像描述

Kob*_*ohn 5

它[似乎networkx没有为排列图表提供太多,但我只触及了几次,所以我不能肯定地说.我找不到办法去做你要问的事.

但是,我尝试使用graphviz(必须先安装)才能完成它.排名方法的功劳归于此SO答案.

复制粘贴示例

import networkx as nx

ranked_node_names = [['start'],
                     [1, 2, 3],
                     ['a', 'b', 'c'],
                     ['end']]
node_edges = [('start', 2),
              ('start', 3),
              (2, 'b'),
              ('b', 'end'),
              ('a', 'end')]

# graph and base nodes/edges in networkx
G = nx.DiGraph()
for rank_of_nodes in ranked_node_names:
    G.add_nodes_from(rank_of_nodes)
G.nodes(data=True)
G.add_edges_from(node_edges)
# I don't know a way to automatically arrange in networkx so using graphviz
A = nx.to_agraph(G)
A.graph_attr.update(rankdir='LR')  # change direction of the layout
for rank_of_nodes in ranked_node_names:
    A.add_subgraph(rank_of_nodes, rank='same')
# draw
A.draw('example.png', prog='dot')
Run Code Online (Sandbox Code Playgroud)

默认输出

在此输入图像描述

LR(左 - 右)输出

在此输入图像描述