我想繪製一個二部圖,左邊的節點與右邊的節點不同。我使用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