0

I have a multigraph, with multiple edges per pair of nodes. How can I label all the edges with text(1,2,3,4,5)?

pos = nx.random_layout(G)
nx.draw_networkx_nodes(G, pos, node_color = 'r', node_size = 100, alpha = 1)
ax = plt.gca()
for e in G.edges:
    ax.annotate("",
                xy=pos[e[0]], xycoords='data',
                xytext=pos[e[1]], textcoords='data',
                arrowprops=dict(arrowstyle="->", color="0.5",
                                shrinkA=5, shrinkB=5,
                                patchA=None, patchB=None,
                                connectionstyle="arc3,rad=rrr".replace('rrr',str(0.3*e[2])
                                ),
                                ),
                )
plt.axis('off')
plt.show()              

After running the codes above, I will get the image shown here.

enter image description here

But how can I label the edges like this?

enter image description here

Image and source code taken from: Drawing multiple edges between two nodes with networkx

R_abcdefg
  • 145
  • 1
  • 11

1 Answers1

0

You could use ax.text to add text. You'll have to play around with the x and y parameters (using e[2]) to stop the labels overlaying.

G=nx.MultiGraph ([(1,2,{'label':'A'}),(1,2,{'label':'B'}),(1,2,{'label':'C'}),(3,1,{'label':'D'}),(3,2,{'label':'E'})])
pos = nx.random_layout(G)
nx.draw_networkx_nodes(G, pos, node_color = 'r', node_size = 100, alpha = 1)
ax = plt.gca()
for e in G.edges(keys=True,data=True):
    print(e)
    ax.annotate("",
                
                xy=pos[e[0]], xycoords='data',
                xytext=pos[e[1]], textcoords='data',
                arrowprops=dict(arrowstyle="->", color="0.5",
                                shrinkA=5, shrinkB=5,
                                patchA=None, patchB=None,
                                connectionstyle="arc3,rad=rrr".replace('rrr',str(0.3*e[2])
                                ),
                                ),
                )
    ax.text((pos[e[0]][0]+pos[e[1]][0])*0.5,(pos[e[0]][1]+pos[e[1]][1])*0.5,str(e[3]['label']))
plt.axis('off')
plt.show()
Lee
  • 29,398
  • 28
  • 117
  • 170
  • Thank you @atomh33ls ! But is there anyway to find a way to fix the orientation of the chart so I don’t need to adjust the x and y coords of the text everytime? I’m trying to make a dynamic function to plot a graph visualisation, so the number of nodes, number of edges will differ everytime. – R_abcdefg Mar 25 '21 at 17:28
  • @R_abcdefg Yes this should work regardless (as long as your graph edges have a `label` property. You will need to figure out the x and y co-ords to take into account the parallel edges (calculated using the `arc3` parameter in the example) – Lee Mar 25 '21 at 20:50
  • Thanks! Could you explain what you mean by this? You'll have to play around with the x and y parameters (using e[2]). My main problem now is the overlapping. I cannot seem to get that out of the way. – R_abcdefg Mar 26 '21 at 02:27