networkx在左侧和右侧分别绘制节点-graphviz,python
我使用以下代码将以“n”开头的节点涂成灰色,将以“m”开头的节点涂成红色networkx在左侧和右侧分别绘制节点-graphviz,python,python,networkx,draw,graphviz,Python,Networkx,Draw,Graphviz,我使用以下代码将以“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, po
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)
如下图所示,此操作成功:
但是,我尝试将该图绘制为二部图,这意味着所有红色节点将在左侧对齐,所有灰色节点将在左侧对齐,但没有成功。有什么想法吗
*修正了@Mohammed Kashif answer,但是右侧注释不能显示所有:
您可以使用NetworkX中定义的
两部分布局。你可以阅读更多关于它的内容。您需要传递属于两部分布局的任一集合的节点列表
下面是使用二分体布局的工作示例。我冒昧地定义了与您类似的图的节点
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)
以下是输出:
参考文献:
你也可以在Google Colab笔记本上查看代码