我使用networkx
和matplotlib
繪製網絡圖。我已將每個節點以浮點形式(最多兩位小數點)與標籤相關聯。我希望標籤在圖中更清晰可見。是否有任何解決方法可以提高標籤的可見度?如何使節點標籤在matplotlib中更清晰可見
更新: 我發現了一個類似的問題here,並試圖以應用解決方案。事實證明,這個解決方案工作得非常糟糕。
的代碼如下:
label_ratio = 1.0/8.0
pos_labels = {}
#For each node in the Graph
for node in network.graph.nodes():
#Get the node's position from the layout
x,y = network.position[node]
#Get the node's neighbourhood
N = network.graph[node]
#Find the centroid of the neighbourhood. The centroid is the average of the Neighbourhood's node's x and y coordinates respectively.
#Please note: This could be optimised further
cx = sum(map(lambda x:pos[x][0], N))/len(pos)
cy = sum(map(lambda x:pos[x][1], N))/len(pos)
#Get the centroid's 'direction' or 'slope'. That is, the direction TOWARDS the centroid FROM aNode.
slopeY = (y-cy)
slopeX = (x-cx)
#Position the label at some distance along this line. Here, the label is positioned at about 1/8th of the distance.
pos_labels[node] = (x+slopeX*label_ratio, y+slopeY*label_ratio)
nx.draw(G, pos, ax=axis, node_size=20, with_labels=False)
nx.draw_networkx_labels(G, pos_labels, labels, font_size=7, font_color='b', ax=axis)
您可以指定字體和相對位置,這是你的意思嗎? – kabanus
增加字體的問題是標籤傾向於重疊。另一方面,佈局/網絡佈局是固定的,應該只顯示如圖所示。我希望有一種方法可以讓標籤出現在節點的頂部(或者可能在旁邊),並且不會與其他標籤重疊。這有點苛刻,但也許可能存在解決方案。如果沒有,那麼哦。 – meraxes
這就是我所說的相對位置,字體也是顏色 - 例如,紅色會顯示在節點的頂部(如果仔細觀察,標籤位於頂部,顏色可能不一致)。請發佈您用於製作標籤的代碼並將其關聯。 – kabanus