Abheek Sambyal
Abheek Sambyal

Reputation: 21

Nodes in graph not showing the right label

Have imported the below matrix using pandas.

     name1 name2 name3
name1 0     1     0
name2 1     0     1
name3 0     0     1

The graph is showing the nodes as numerics 1, 2, 3. However, I want the nodes to be name1, name2, name3

See the code I am using:

import pandas as pd
import networkx as nx
datamuse = pd.read_csv('NetworkDatasheet.csv',index_col=0)
print(datamuse)
G = nx.DiGraph(datamuse.values)
nx.draw_random(G, with_labels=True)

Upvotes: 1

Views: 276

Answers (1)

Kirell
Kirell

Reputation: 9818

Here is a working solution. To get rid of the Dataframe I included the label directly in the Graph attributes.

import pandas as pd
import networkx as nx

df = pd.DataFrame([[0, 1, 0], [1, 0, 1], [0, 0, 1]], 
                  index=['name1', 'name2', 'name3'], 
                  columns=['name1', 'name2', 'name3'])

# You code works, here it's more explicit
G = nx.from_numpy_matrix(df.values, create_using=nx.DiGraph())
# Set labels in each node under the key 'label', create a dict{0: 'name1', ...}
nx.set_node_attributes(G, 'label', dict(zip(xrange(len(df)), df.index.values)))
# Draw the network and specify the labels
nx.draw_random(G, with_labels=True, labels=nx.get_node_attributes(G, 'label'))

Upvotes: 1

Related Questions