[英]networkx draw separate nodes to left and right side - graphviz, python
I use the following code to colour the nodes that start with "n" as gray and the nodes starting with "m" letter with red colour我使用以下代码将以“n”开头的节点着色为灰色,将以“m”字母开头的节点着色为红色
color_map = []
for node in c:
strnode = str(node)
if strnode.startswith("m"):
color_map.append('red')
else:
color_map.append('gray')
nx.draw(c, pos=nx.nx_agraph.graphviz_layout(c, prog='circo'),node_size=140, scale= 2, node_color=color_map,with_labels=True)
This works successfully as the picture shows below:这成功地工作,如下图所示:
However, I have tried to draw the graph as a bipartite graph, meaning all the Red nodes to be aligned on the left side and all the gray nodes on the left side with no success.但是,我尝试将图形绘制为二分图,这意味着所有红色节点都在左侧对齐,而所有灰色节点都在左侧对齐,但没有成功。 Any ideas?
有任何想法吗?
*Fixed with @Mohammed Kashif answer, however the right side notes cannot displayed all: *修复了@Mohammed Kashif 的回答,但右侧的注释无法全部显示:
You can use bipartite_layout
defined in NetworkX.您可以使用 NetworkX 中定义的
bipartite_layout
。 You can read more about it here .你可以在这里阅读更多关于它的信息。 You need to pass a list of nodes belonging to either of the sets of the bipartite layout.
您需要传递属于任一二分布局集的节点列表。
Below is the working example which uses the bipartite_layout
.下面是使用
bipartite_layout
的工作示例。 I took the liberty of defining the nodes of the Graph similar to yours.我冒昧地定义了与您类似的 Graph 节点。
import networkx as nx
# Define the nodes of the Graph
nodes_list = ["m1", "n1", "m2", "n2", "m3", "n3", "m4", "n4"]
# Define the Graph and add the nodes/edges
G = nx.DiGraph()
G.add_nodes_from(nodes_list)
G.add_edges_from([("m1", "n3"), ("m2", "n1"), ("n4", "m3")])
color_map = []
# This will store the nodes belonging to one set of
# the bipartite graph. In this case, the nodes which
# start with "m"
one_side_nodes = []
for node in G:
strnode = str(node)
if strnode.startswith("m"):
color_map.append('red')
# Add the node to the list
one_side_nodes.append(node)
else:
color_map.append('gray')
# Now in the `pos` attribute pass in nx.bipartite_layout,
# with the list of nodes belonging to one set of the bipartite
# graph, i.e. one_side_nodes.
nx.draw(G, pos=nx.bipartite_layout(G, one_side_nodes),node_size=140,
scale= 2, node_color=color_map, with_labels=True)
Here is the output:这是 output:
References:参考:
You can also view the code on Google Colab Notebook here .您还可以在此处查看 Google Colab Notebook 上的代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.