2

I am trying to draw a visualization for a network using three different lists which form 3 types of nodes

The below code is working. as shown, it takes two lists. userId, ratings.

However, I want my graph to be tri-partite. That is, { 'user':userId, 'review':ratings, 'product':prodId}

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

I know that, from_pandas_edgelist only accepts 'from' and 'to'. But, I dont know the alternative to it.

Basically, my graph has edges (user,ratings) and (ratings, products). I get two seperate visualizations i want them in one.

I am new to visualising networks and need some help on this.

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) 

sandilya M
  • 89
  • 1
  • 7

1 Answers1

4

well, it's been a long time now but as it might be to someone else's use, you can do like below and it is not limited to a certain number of sets, I have up to five-partites already. I solved my problem based on this answer. here is what I did :

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)

you can ofcourse add other parameters to .draw function or add a savefig to it.

note: you will have to create the edges for your problem but the code shows how to make and show the tripartite graph.

Omid S.
  • 731
  • 7
  • 15