Python 如何在一个数据框中绘制三列无向图,形成3种不同类型的节点(三方)?

Python 如何在一个数据框中绘制三列无向图,形成3种不同类型的节点(三方)?,python,matplotlib,graph,networkx,Python,Matplotlib,Graph,Networkx,我试图用三个不同的列表来绘制一个网络的可视化,这三个列表形成了3种类型的节点 下面的代码正在工作。如图所示,它包含两个列表。用户ID,分级 然而,我希望我的图是三分的。 即,{'user':userId,'review':ratings,'product':prodId} G=nx.来自于edgelist(用户审查图,'用户','审查','产品') 我知道,from_pandas_edgelist只接受“from”和“to”。但是,我不知道还有什么办法可以替代它 基本上,我的图有边(用户、评级)

我试图用三个不同的列表来绘制一个网络的可视化,这三个列表形成了3种类型的节点

下面的代码正在工作。如图所示,它包含两个列表。用户ID,分级

然而,我希望我的图是三分的。 即,{'user':userId,'review':ratings,'product':prodId}

G=nx.来自于edgelist(用户审查图,'用户','审查','产品')

我知道,from_pandas_edgelist只接受“from”和“to”。但是,我不知道还有什么办法可以替代它

基本上,我的图有边(用户、评级)和边(评级、产品)。 我有两个不同的视觉效果,我希望它们在一个

我不熟悉可视化网络,在这方面需要一些帮助

import networkx as nx
import matplotlib.pyplot as plt

user_review_graph = pd.DataFrame({ 'user':userId, 'review':ratings})
user_review_graph
G=nx.from_pandas_edgelist(user_review_graph, 'user', 'review')



pos=nx.spring_layout(G)
nx.draw(G,pos,node_color='#A0CBE2',edge_color='#BB0000',width=2,edge_cmap=plt.cm.Blues,with_labels=True, font_weight=500,font_size=7)
#plt.show()
plt.savefig("test2.png", dpi=500, facecolor='w', edgecolor='w',orientation='portrait', papertype=None, format=None,transparent=False, bbox_inches=None, pad_inches=0.1) 


好吧,这已经是一个很长的时间了,但它可能是其他人的使用,你可以像下面这样做,它不限于一定数量的集合,我已经有多达五个部分。 我根据答案解决了我的问题。 以下是我所做的:

BG = nx.Graph()

# add nodes here
BG.add_nodes_from(users, bipartite=0)
BG.add_nodes_from(products, bipartite=1)
BG.add_nodes_from(reviews, bipartite=2)

# add edges here
BG.add_edges_from(user_product_edges)
BG.add_edges_from(product_review_edges)


nodes = BG.nodes()
# for each of the parts create a set 
nodes_0  = set([n for n in nodes if  BG.nodes[n]['bipartite']==0])
nodes_1  = set([n for n in nodes if  BG.nodes[n]['bipartite']==1])
nodes_2  = set([n for n in nodes if  BG.nodes[n]['bipartite']==2])

# set the location of the nodes for each set
pos = dict()
pos.update( (n, (1, i)) for i, n in enumerate(nodes_0) ) # put nodes from X at x=1
pos.update( (n, (2, i)) for i, n in enumerate(nodes_1) ) # put nodes from Y at x=2
pos.update( (n, (3, i)) for i, n in enumerate(nodes_2) ) # put nodes from X at x=1

nx.draw(BG, pos=pos)
当然,您可以向
.draw
函数添加其他参数,或向其添加
savefig

注意:您必须为您的问题创建边,但代码显示了如何制作和显示三方图