简体   繁体   English

在 NetworkX 中绘制将绘图区域划分为 3 的图形

[英]in NetworkX draw the graph dividing the plot area in 3

I have a graph in Networkx with different info inside.我在 Networkx 中有一个图表,里面有不同的信息。 The graph nodes look like this:图形节点如下所示:

G = nx.DiGraph()
G.add_node(shape1, level=1)
G.add_node(shape2, level=2)
G.add_node(shape3, level=2)
G.add_node(shape4, level=3)
...

I want to draw the graph in order to have all the shapes at level 1 at the top of the plot, all the shapes in level 3 positioned in the lower part of the plot and all the shapes at level 2 in the middle.我想绘制图表,以便将第 1 级的所有形状都放在绘图的顶部,将第 3 级的所有形状放在绘图的下部,将第 2 级的所有形状放在中间。 There are maximum 3 levels.最多有3个级别。

I have been reading documentations from NetworkX, but till now I used only this random positioning of the nodes:我一直在阅读 NetworkX 的文档,但到目前为止,我只使用了节点的这种随机定位:

pos = nx.spring_layout(G) nx.draw(G, pos) . pos = nx.spring_layout(G) nx.draw(G, pos)

Do you know any smarter way to position the nodes of the graph as I want?你知道任何更聪明的方法来定位我想要的图形节点吗?

PS: The desired output would be roughly like this: PS:所需的输出大致是这样的:在此处输入图像描述

I don't need to draw also the lines for dividing the levels, I just put them to make it clear what I need.我也不需要画线来划分层次,我只是把它们放在清楚我需要什么上。

The layout "dot" provided the interface to graphviz seems to do what you are looking for. 提供给graphviz的界面的布局“点”似乎可以满足您的需求。 While it works for this simple graph you've provided, you may need to tweak the output for larger more complicated graphs. 当它适用于您提供的这个简单图形时,您可能需要调整输出以获取更大,更复杂的图形。

import networkx as nx

G = nx.DiGraph()
G.add_node(1,level=1)
G.add_node(2,level=2)
G.add_node(3,level=2)
G.add_node(4,level=3)

G.add_edge(1,2)
G.add_edge(1,3)
G.add_edge(2,4)

import pylab as plt
nx.draw_graphviz(G, node_size=1600, cmap=plt.cm.Blues,
                 node_color=range(len(G)),
                 prog='dot')
plt.show()

在此处输入图片说明

Updated answer for NetworkX 2.6.2: NetworkX 2.6.2 的更新答案:

pos = nx.nx_pydot.graphviz_layout(G, prog="dot")
nx.draw(G, pos=pos, with_labels=True, font_weight='bold')
plt.show()

(make sure you have pydot installed) (确保您已安装pydot

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM