I'm trying to generate a networkx graph from a dataframe using the code below:
import pandas as pd
import numpy as np
import networkx as nx
data = [[0,0,0,1], [1,0,0,1], [1,0,0,1], [0,0,0,0]]
df = pd.DataFrame(data, columns=['S1', 'S2', 'S3', 'S4'])
df.index = ['S1', 'S2', 'S3', 'S4']
G = nx.DiGraph(df.values, with_labels=True)
nx.draw(G)
However, the graphs outputs without the names of the node being shown, which looks like below
I tried to label the nodes in the graph using the networkx relabel_nodes
however without luck
G = nx.relabel_nodes(G, dict(enumerate(df.columns)))
nx.draw(G)
Is there a way wherein I can label the nodes of the networkx graph as S1, S2, S3, S4
?
CodePudding user response:
The renaming should be a mapping that has old node identifiers as keys and new node identifier as values (a dictionary, basically):
mapping = {0: "S1", 1: "S2", 2: "S3", 3: "S4"}
H = nx.relabel_nodes(G, mapping)
print(H.nodes)
# ['S1', 'S2', 'S3', 'S4']