nsx
nsx

Reputation: 705

NetworkX and Matplotlib - Misplaced Text Labels

The following code tries to place a label for each node apart from the one that is by default included by NetworkX/Matplotlib. The original positions of the nodes are obtained through the call to "nx.spring_layout(g)".

The problem is that, when it comes to draw with Matplotlib the labels, the latter are misplaced, as it can be seen in the attached graph.

Should I be doing something differently?

import logging
import networkx as nx
import matplotlib.pyplot as plt

__log = logging.getLogger(__name__)
g = nx.Graph()

nodes = ['shield', 'pcb-top', 'pcb-config', 'chassis']
for k in nodes:
    g.add_node(k)

plt.figure(figsize=(8, 11), dpi=150)
nx.draw(g, with_labels=True)

node_cfg = nx.spring_layout(g)
for k, node in node_cfg.items():
    __log.debug('node = %s @(%.6f, %.6f)', k, node[0], node[1])
    plt.text(node[0], node[1], k, bbox={'color': 'grey'})

plt.savefig('test.png')

Misplaced Labels

Upvotes: 1

Views: 424

Answers (1)

Aric
Aric

Reputation: 25289

Use the same position information for the network drawing as for the labels.

node_cfg = nx.spring_layout(g)
plt.figure(figsize=(8, 11), dpi=150)
nx.draw(g, pos=node_cfg, with_labels=True)

Upvotes: 2

Related Questions