From 2 column csv to 2 color NetworkX graph

400 views Asked by At

I want to create a large networkx graph connecting users to the videos they watch like user -> video in a social graph or network type of graph. There are about 9000 user nodes and 20000 video nodes.

Example CSV File

user, video

1, 11

2, 11

3, 11

4, 12

5, 12

5, 13

What I am trying?

G=nx.read_edgelist("test.csv", delimiter = ',', data=['user','highlight'], create_using=nx.Graph())

nx.draw(G)

What I get: A graph with all red nodes.

What I want: I want the user nodes to be red and the video nodes to be blue. Thank you in advance for your help.

1

There are 1 answers

2
jujuBee On BEST ANSWER
import networkx as nx
import csv
import matplotlib.pyplot as plt;

file_edges=csv.reader(open('test.csv','rb'));

G=nx.Graph();
users=[];
video=[];
for row in file_edges:
    G.add_node(row[0],type='user');
    users.append(row[0]);
    G.add_node(row[1],type='video');
    video.append(row[1]);
    G.add_edge(row[0],row[1]);

pos=nx.spring_layout(G) # positions for all nodes
fig=plt.figure(1)
ax=fig.add_subplot(111);
nx.draw_networkx_nodes(G,pos=pos,nodelist=users,with_labels=True,node_size=150,node_color='red',node_shape='s', width=1.75,linewidths=0.2,font_size=5,font_family='serif')
nx.draw_networkx_nodes(G,pos=pos,nodelist=video,with_labels=True,node_size=150,node_color='blue',node_shape='s', width=1.75,linewidths=0.2,font_size=5,font_family='serif')
nx.draw_networkx_edges(G, pos=pos, edgelist=G.edges(), width=3, edge_color='black');
nx.draw_networkx_labels(G,pos,nodelabels=G.nodes(),font_size=8,font_family='serif',font_color='white',font_weight='bold')
ax.legend(['users','video'],loc=2,numpoints=1,scatterpoints=1,prop={'size':10}) # Scatterpoints will show the node marker (say square) only once
plt.gcf()
plt.axis('off')
plt.show()