I'm using networkx
and matplotlib
to draw a graph of a network. I've associated with each node a label in the form of a float (up to two decimal points). I was hoping for the labels to be more visible in the graph. Is there any sort of workaround that will allow for better label visibility?
Updates: I found a similar question here, and have tried to apply the solution. The solution works pretty badly as it turned out.
The code is as follows:
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)