避免在 NetworkX 的边缘切割标签 [英] Avoid labels being cut at the edges in NetworkX

查看:56
本文介绍了避免在 NetworkX 的边缘切割标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 python networkx lib 绘制节点关系图.代码如下:

将 networkx 导入为 nx导入 matplotlib.pyplot 作为 pltG = 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()

一切正常.图为:

但是,我想将标签放在节点之外.然后我调整标签的位置.代码是:

将 networkx 导入为 nx导入 matplotlib.pyplot 作为 pltG = 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()

那么图是:

问题是,标签没有完全显示,而是超出了边界.那么如何正常显示标签呢?谢谢.

解决方案

您可以在

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.

解决方案

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

这篇关于避免在 NetworkX 的边缘切割标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆