python 标签位置_python – NetworkX节点标签的相对位置

为了显示轴外的标签,您需要使轴与图相比较小,例如,通过在轴周围引入大的余量.您还需要设置文本的剪辑状态,以使其不被轴切断.

根据边界框的宽度定位标签需要首先将边界框从显示坐标转换为数据坐标.

完整解决方案

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

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值