I have a piece of code to draw a graph. For this I am reading some files to get the nodes and the weights.
plt.title('Grafo Completo Github')
pos = nx.spring_layout(g)
nx.draw(g, with_labels=True, node_color="skyblue", font_size=8)
nx.draw_networkx_edge_labels(g, pos=pos, edge_labels=nx.get_edge_attributes(g, 'weight'), label_pos=1, rotate=False, font_size=8)
plt.savefig("grafo_github.jpg")
plt.show()
But, this produces the image below. How can I correct the positions of edge labels?
Edge Labels in wrong position:
The real mistake seems to be the value of the attribute label_pos
.
From the docs of draw_networkx_edge_labels
:
label_pos (float) – Position of edge label along edge (0=head, 0.5=center, 1=tail)
By using label_pos=1
the labels were appearing behind the nodes since their position is also on 'the edge tail'.
Changing this value to 0.5
should solve the issue:
nx.draw_networkx_edge_labels(T, pos, edge_labels=nx.get_edge_attributes(T, 'weight'), label_pos=0.5, rotate=False, font_size=8)
Or, since 0.5
is default, simply remove it.
pos = nx.spring_layout(g)
nx.draw(g, pos=pos, with_labels=True, node_color="skyblue", font_size=8)
nx.draw_networkx_edge_labels(T, pos, edge_labels=nx.get_edge_attributes(T, 'weight'), rotate=False, font_size=8)