Forklift17
Forklift17

Reputation: 2477

Plotting isolated nodes in NetworkX

import networkx as nx
import numpy as np
from scipy.sparse import coo_matrix #coordinate sparse matrices

A = np.zeros([4,4])
A[0,1] = A[1,2] = 1
S = coo_matrix(A)
edges = np.r_[[S.row], [S.col]].T
G = nx.Graph()
G.add_edges_from(edges)
nx.draw(G)

When I run that script, I get this:

3-node network

But there are four nodes. How can I get the isolated fourth node to show?

Upvotes: 1

Views: 917

Answers (1)

fuglede
fuglede

Reputation: 18201

By only adding the edges to the graph, networkx has no way of knowing about the additional vertices; all it's doing is adding the vertices of each edge that you're providing. If, instead, you explicitly add all vertices, then you're good to go:

G = nx.Graph()
G.add_nodes_from(range(len(A)))
G.add_edges_from(edges)
nx.draw(G)

enter image description here

Upvotes: 4

Related Questions