1

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

1 Answer 1

2

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.