I'm drawing an undirected, weighted graph in networkx and wish to label each edge with it corresponding weight. I'm able to do this, but I'm having problems rounding off the edge label values so that the resulting diagram isn't too cluttered.
We'll assume I've already created my adjacency matrix, A, and that labels_dict is a dictionary whose values are text labels for each node, e.g. 'T8-P8'.
import networkx as nx
G=nx.from_numpy_matrix(A)
pos=nx.spring_layout(G)
nx.draw_networkx_nodes(G,pos,nodelist=[j for j in
range(0,len(A))],node_color='gray',node_size=1000,ax=None,alpha=0.8)
nx.draw_networkx_labels(G,pos,labels_dict,font_size=17)
nx.draw_networkx_edges(G,pos,width=1.0,alpha=0.5)
# below I attempt to round off the edge label values to 2 decimal places using numpy's "around" function.
edge_labels=dict([((u,v,),np.around(d['weight'],2))
for u,v,d in G.edges(data=True)])
nx.draw_networkx_edge_labels(G,pos,edge_labels=edge_labels)
ax=plt
ax.axis('off')
fig = ax.gcf()
plt.show()
The resulting graph looks as follows, which shows how edge labels haven't been rounded off:
Pass your labels in as strings (not floats) and do string formatting with string formatting tools:
edge_labels = dict([((u,v,), f"{d['weight']:.2f}") for u,v,d in G.edges(data=True)])
Not that I have ever attempted to do it the way you did. Nooo.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With