【问题标题】:How to draw a undirected graph with three columns in a dataframe which form 3 different types of nodes(tripartite)?如何在数据框中绘制具有三列的无向图,形成 3 种不同类型的节点(三方)?
【发布时间】:2019-08-09 09:48:36
【问题描述】:

我正在尝试使用形成 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) 

【问题讨论】:

    标签: python matplotlib graph networkx


    【解决方案1】:

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

    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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-05
      • 1970-01-01
      • 2021-11-09
      • 1970-01-01
      • 2019-01-29
      • 1970-01-01
      相关资源
      最近更新 更多