[英]NetworkX node labels relative position
我正在努力解決以下問題。 我想繪制一個大約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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.