Helix Herry
Helix Herry

Reputation: 327

how to add attributes to ndarrary adjacency matrix in networkx?

Orginally I have a hashtag co-occ network stored in dataframe like this:

0        ['#A', '#B', '#C', '#D]
1        ['#A', '#E']
2        ['#b', '#c', '#D']
3        ['#C', '#D']

Then I converted it into an adjacency matrix like this:

,#A,#B,#C,#D,#E,#F,#G,#H,#I,#J,#K
#A,0,1,1,0,1,1,1,1,0,1,0
#B,1,0,0,0,1,1,1,1,0,1,0
#C,1,0,0,0,1,1,1,1,0,1,0
...

I want to load the net into networkx in order to do the math and draw the graph. So I use the np.genfromtext method to load the data into ndarrary. I have loaded the data successfully but I don't know how to label them.

mydata = genfromtxt(src5+fname[0], delimiter=',',encoding='utf-8',comments='**')
adjacency = mydata[1:,1:]
print(adjacency)


[[0. 0. 0. ... 0. 0. 0.]
 [0. 0. 0. ... 0. 0. 0.]
 [0. 0. 0. ... 0. 0. 0.]
 ...
 [0. 0. 0. ... 0. 0. 0.]
 [0. 0. 0. ... 0. 0. 0.]
 [0. 0. 0. ... 0. 0. 0.]]

By the way, can I just input the data from the original dataframe instead of using the adjacency matrix?

Upvotes: 2

Views: 777

Answers (1)

ilia
ilia

Reputation: 640

You can display both edge and node labels.

Suppose you have adjacency matrix and hashtag list:

# matrix from question
A = np.array([[0,1,1,0,1,1,1,1,0,1,0],
[1,0,0,0,1,1,1,1,0,1,0],
[1,0,0,0,1,1,1,1,0,1,0],
[0,0,0,0,0,0,0,0,0,0,0],
[1,1,1,0,0,0,0,0,0,0,0],
[1,1,1,0,0,0,0,0,0,0,0],
[1,1,1,0,0,0,0,0,0,0,0],
[1,1,1,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0],
[1,1,1,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0]])

labels = ['#A','#B','#C','#D','#E','#F','#G','#H','#I','#J','#K']

Here is some visulisation example:

import networkx as nx
import numpy as np
import matplotlib.pyplot as plt

# labels to dict
labels = {k: v for k, v in enumerate(labels)}

# create graph and compute layout coords
G = nx.from_numpy_matrix(A, parallel_edges=True)
# k controls node closeness, 0 <= k <= 1
coord = nx.spring_layout(G, k=0.55, iterations=20)

# optional: set label coords a bit upper the nodes
node_label_coords = {}
for node, coords in coord.items():
    node_label_coords[node] = (coords[0], coords[1] + 0.04)

# draw the network, node and edge labels
plt.figure(figsize=(20, 14))
nx.draw_networkx_nodes(G, pos=coord)
nx.draw_networkx_edges(G, pos=coord)
nx.draw_networkx_edge_labels(G, pos=coord)
nx.draw_networkx_labels(G, pos=node_label_coords, labels=labels)

resultion network

You can find more info on the adjacency matrix graph creation at the NetworkX documentation

Update:
Refer to set_node_attributes function to add attributes to your network nodes

degree_centr = nx.degree_centrality(G)
nx.set_node_attributes(G, degree_centr, "degree")
nx.write_gexf(G, "test.gexf")

After saving graph to file with write_gexf, you'll have a file with attributes suitable for Gephi.

Upvotes: 2

Related Questions