python – NetworkX节点标签的相对位置
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python – NetworkX节点标签的相对位置,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2743字,纯文字阅读大概需要4分钟。
内容图文
我正在努力解决以下问题.我想绘制一个大约100个节点的圆形图,我必须根据之前的分类手动定位它们.这些节点有一个指定的标签,用不同的文本长度描述它们,我想把这个标签放在节点附近.下图是我想要获得的(我绘制蓝色圆圈只是为了表明标签在外围完美对齐):
https://i.stack.imgur.com/Qre0Z.png
到目前为止,我只是画了这个:https://i.stack.imgur.com/U7bZG.png
这是MWE:
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
n = 7
G = nx.complete_graph(n)
node_list = sorted(G.nodes())
angle = []
angle_dict = {}
for i, node in zip(xrange(n),node_list):
theta = 2.0*np.pi*i/n
angle.append((np.cos(theta),np.sin(theta)))
angle_dict[node] = theta
pos = {}
for node_i, node in enumerate(node_list):
pos[node] = angle[node_i]
labels = {0:'zero',1:'oneone',2:'twotwo',3:'threethreethree',4:'fourfourfourfour',5:'fivefivefivefivefive',6:'sixsixsixsixsixsix'}
# figsize is intentionally set small to condense the graph
f = plt.figure(figsize=(2,2))
r = f.canvas.get_renderer()
plt.axis('equal')
nx.draw(G,pos=pos,with_labels=True)
description = nx.draw_networkx_labels(G,pos,labels=labels)
for node, t in description.items():
t.set_rotation(angle_dict[node]*360.0/(2.0*np.pi))
plt.show()
我想我必须添加和玩
x, y = t.get_position()
bb = t.get_window_extent(renderer=r)
radius = 1.0+2.0*bb.width/r.width
t.set_position((radius*x,radius*y))
在我设置标签旋转的循环中.但是,我不知道如何正确设置它以及如何避免裁剪画布.
解决方法:
为了显示轴外的标签,您需要使轴与图相比较小,例如,通过在轴周围引入大的余量.您还需要设置文本的剪辑状态,以使其不被轴切断.
根据边界框的宽度定位标签需要首先将边界框从显示坐标转换为数据坐标.
完整解决方案
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
n = 7
G = nx.complete_graph(n)
node_list = sorted(G.nodes())
angle = []
angle_dict = {}
for i, node in zip(xrange(n),node_list):
theta = 2.0*np.pi*i/n
angle.append((np.cos(theta),np.sin(theta)))
angle_dict[node] = theta
pos = {}
for node_i, node in enumerate(node_list):
pos[node] = angle[node_i]
labels = {0:'zero',1:'oneone',2:'twotwo',3:'threethreethree',4:'fourfourfourfour',5:'fivefivefivefivefive',6:'sixsixsixsixsixsix'}
# figsize is intentionally set small to condense the graph
fig, ax = plt.subplots(figsize=(5,5))
margin=0.33
fig.subplots_adjust(margin, margin, 1.-margin, 1.-margin)
ax.axis('equal')
nx.draw(G,pos=pos,with_labels=True, ax=ax)
description = nx.draw_networkx_labels(G,pos,labels=labels)
r = fig.canvas.get_renderer()
trans = plt.gca().transData.inverted()
for node, t in description.items():
bb = t.get_window_extent(renderer=r)
bbdata = bb.transformed(trans)
radius = 1.2+bbdata.width/2.
position = (radius*np.cos(angle_dict[node]),radius* np.sin(angle_dict[node]))
t.set_position(position)
t.set_rotation(angle_dict[node]*360.0/(2.0*np.pi))
t.set_clip_on(False)
plt.show()
内容总结
以上是互联网集市为您收集整理的python – NetworkX节点标签的相对位置全部内容,希望文章能够帮你解决python – NetworkX节点标签的相对位置所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。