gpt4 book ai didi

python - networkx 在左侧和右侧绘制单独的节点 - graphviz,python

转载 作者:行者123 更新时间:2023-12-04 09:32:13 29 4
gpt4 key购买 nike

我使用以下代码将以“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)
这工作成功,如下图所示:
enter image description here
但是,我试图将图形绘制为二部图,这意味着所有红色节点都在左侧对齐,所有灰色节点都在左侧对齐,但没有成功。有任何想法吗?
*修复了@Mohammed Kashif 的答案,但右侧注释无法全部显示:
enter image description here

最佳答案

您可以使用 bipartite_layout在 NetworkX 中定义。您可以阅读更多相关信息 here .您需要传递属于二部布局的任何一组的节点列表。
下面是使用 bipartite_layout 的工作示例.我冒昧地定义了与您类似的图形节点。

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)
这是输出:
Bipartite Layout
引用文献:
  • NetworkX: Bipartite Layout

  • 您也可以在 Google Colab Notebook 上查看代码 here .

    关于python - networkx 在左侧和右侧绘制单独的节点 - graphviz,python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62783146/

    29 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com