Yang
Yang

Reputation: 53

Avoid labels being cut at the edges in NetworkX

I am using python networkx lib draw a node relation graph. Code like this:

import networkx as nx 
import matplotlib.pyplot as plt

G = nx.Graph()
G.add_edges_from([("leg", 'body'),('body', 'head'),('body','arm'),('arm','hand')])
pos = nx.spring_layout(G)
nx.draw_networkx_nodes(G,pos)
nx.draw_networkx_edges(G,pos)
nx.draw_networkx_labels(G,pos)
plt.show()

Everything is fine. The figure is:

enter image description here

However, I'd like to put the label outside of the node. Then I adjust the position of labels. code is:

import networkx as nx 
import matplotlib.pyplot as plt

G = nx.Graph()
G.add_edges_from([("leg", 'body'),('body', 'head'),('body','arm'),('arm','hand')])
pos = nx.spring_layout(G)
nx.draw_networkx_nodes(G,pos)
nx.draw_networkx_edges(G,pos)
# nx.draw_networkx_labels(G, pos)
nx.draw_networkx_labels(G, pos = {k:([v[0], v[1]+0.1]) for k,v in pos.items()})

plt.show()

Then the figure is:

enter image description here

The question is, the label do not display totally, but exceed the boundary. so how can I display the labels normally? thanks.

Upvotes: 5

Views: 1996

Answers (1)

yatu
yatu

Reputation: 88305

You could set the scale parameter in nx.spring_layout to a low value to scale down the positions. It basically applies a scale factor to the node positions, so the nodes are positioned in a box of size [0,scale]. Here's an example:

pos = nx.spring_layout(G, scale=0.2)
nx.draw_networkx_nodes(G,pos)
nx.draw_networkx_edges(G,pos)
y_off = 0.02
nx.draw_networkx_labels(G, pos = {k:([v[0], v[1]+y_off]) for k,v in pos.items()})

enter image description here

Upvotes: 3

Related Questions