Avoid labels being cut at the edges in NetworkX

…衆ロ難τιáo~ 提交于 2020-06-23 11:27:05

问题


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:

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:

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


回答1:


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()})



来源:https://stackoverflow.com/questions/61985381/avoid-labels-being-cut-at-the-edges-in-networkx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!