我想绘制一个二部图,左边的节点与右边的节点不同。我使用networkx和matplotlib来做到这一点。给定一个二部图[(1,3),(2,5),(3,4)],我希望显示[1,2,3],一边是彩色的蓝色,另一边是[4,5]彩色的水色(1,3),(2,5),(3,4)之间。 以下是我的代码。无法显示正确的二分图与网络x
import networkx as nx
import matplotlib.pyplot as plt
def draw_bipartite(edges_list):
left,right = set(),set()
for s,t in edges_list:
right.add(s)
left.add(t)
B = nx.Graph()
B.add_nodes_from(list(right), bipartite=0)
B.add_nodes_from(list(left), bipartite=1)
B.add_edges_from(edges_list)
nodecolor = []
for node in B.nodes():
a = 'blue' if node in list(right) else 'aqua'
nodecolor.append(a)
l,r = nx.bipartite.sets(B)
pos = {}
pos.update((node, (1, index)) for index, node in enumerate(l))
pos.update((node, (2, index)) for index, node in enumerate(r))
nx.draw(B, pos=pos,with_labels = True,node_color=nodecolor)
plt.show()
draw_bipartite([(1, 3), (2, 5), (3, 4)])
在输出中,组[1,2,3]不保留在左侧,我该如何保持左侧以及蓝色?
请在链接“我的输出图”中找到我的代码的输出 – Dhara
顺便说一下,'list in(right)'中的节点效率非常低。 '右边的节点好得多 – Joel