首页 > 解决方案 > 如何在数据框中绘制具有三列的无向图,形成 3 种不同类型的节点(三方)?

问题描述

我正在尝试使用形成 3 种类型节点的三个不同列表为网络绘制可视化

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

但是,我希望我的图表是三方的。即 { 'user':userId, 'review':ratings, 'product':prodId}

G=nx.from_pandas_edgelist(user_review_graph, 'user', 'review','product')

我知道,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) 

标签: pythonmatplotlibgraphnetworkx

解决方案


好吧,现在已经很久了,但可能是为了别人的使用,你可以像下面那样做,它不限于一定数量的套,我已经有多达五部分了。我根据这个答案解决了我的问题。这是我所做的:

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到它。

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


推荐阅读