trav78
trav78

Reputation: 57

How to assign node names to a matrix Networkx?

I am trying to draw a graph in NetworkX. The network connects 30 nodes and about 130 edges. Nodes are set using a matrix with weight

A = [
    [0, 1.51, 0, 1.71, 0],
    [0, 0, 2.11, 1.81, 2.31],
    [0, 0, 0, 1.31, 1.41],
    [0, 0, 0, 0, 1.11],
    [0, 0, 0, 0, 0]]

How to assign the names of the nodes to the matrix from list ("A1", "K2", ... "Z30")? So far, I have only been possible to assign names to numbers.

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

A = [[0, 1.51, 0, 1.71, 0],
     [0, 0, 2.11, 1.81, 2.31],
     [0, 0, 0, 1.31, 1.41],
     [0, 0, 0, 0, 1.11],
     [0, 0, 0, 0, 0]]

G = nx.from_numpy_matrix(np.matrix(A), create_using=nx.DiGraph)

layout = nx.spring_layout(G)
labels = nx.get_edge_attributes(G, "weight")
lab_node = dict((i, str(i)*3) for i in range(5))
nx.draw(G, layout)
nx.draw_networkx_nodes(G, layout, node_size=500)
nx.draw_networkx_edge_labels(G, layout, edge_labels=labels)
nx.draw_networkx_labels(G, layout, labels=lab_node, font_size=10, font_family='sans-serif')
plt.show()

Upvotes: 2

Views: 3649

Answers (2)

Itamar Mushkin
Itamar Mushkin

Reputation: 2895

As a simple workaround, you can turn your adjacency matrix A into a pandas DataFrame whose columns/indices are the labels you want:

import pandas as pd
import networkx as nx

A = [
    [0, 1.51, 0, 1.71, 0],
    [0, 0, 2.11, 1.81, 2.31],
    [0, 0, 0, 1.31, 1.41],
    [0, 0, 0, 0, 1.11],
    [0, 0, 0, 0, 0]]

labels = ['alice', 'bob', 'charlie', 'dan', 'ellie']

To create the DataFrame:

A2 = pd.DataFrame(A, index=labels, columns=labels)

Check the result by drawing it, with no additional setting of labels (showing that we already set it right):

nx.draw_networkx(nx.from_pandas_adjacency(A2))

enter image description here

Upvotes: 2

Sparky05
Sparky05

Reputation: 4892

If your problem is only the drawing you can use the following:

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

A = [[0, 1.51, 0, 1.71, 0],
     [0, 0, 2.11, 1.81, 2.31],
     [0, 0, 0, 1.31, 1.41],
     [0, 0, 0, 0, 1.11],
     [0, 0, 0, 0, 0]]

G = nx.from_numpy_matrix(np.matrix(A), create_using=nx.DiGraph)

layout = nx.spring_layout(G)
labels = nx.get_edge_attributes(G, "weight")
# lab_node = dict((i, "A") for i in range(5))

# a list of the node labels in the right order
raw_labels = ["A1", "K2", "D3", "E4", "Z30"]
lab_node = dict(zip(G.nodes, raw_labels))

nx.draw(G, layout)
nx.draw_networkx_nodes(G, layout, node_size=500)
nx.draw_networkx_edge_labels(G, layout, edge_labels=labels)
nx.draw_networkx_labels(G, layout, labels=lab_node, font_size=10, font_family='sans-serif')
plt.show()

If you want to rename the nodes in your graph, you are probably looking for the relabel_nodes method.

Upvotes: 1

Related Questions