Labeling edges in networkx

Eumel picture Eumel · Nov 3, 2017 · Viewed 19.4k times · Source

I´m programming a basic neural network and want to plot it as a picture. For that i created all the nodes and edges i need.

    for l, j in zip(self.layers, range(len(self.layers))):
        for n, i in zip(l.neurons, range(len(l.neurons))):
            fixed_positions[n.identifier] = (j, i)
    for l in self.layers:
        for n in l.neurons:
            for c, w in zip(n.inconnections, n.inconnectionweights):
               g.add_edge(n.identifier, c.identifier)
    fixed_nodes = fixed_positions.keys()
    pos = nx.spring_layout(g, pos=fixed_positions, fixed=fixed_nodes)

enter image description here

the blue points (imagine them on all edges) are where i want to add a label onto the edges, but i dont know how to do it. Its supposed to work for any reasonable net size, i.e. it shoudl also work for 4, 3 and 2 neurons in the resprective layers.

Answer

Wubin Ding picture Wubin Ding · Nov 6, 2017

Here is an example for ploting edge label in networkx, hope it will help you.

import matplotlib.pyplot as plt
import networkx as nx
edges = [['A','B'],['B','C'],['B','D']]
G = nx.Graph()
G.add_edges_from(edges)
pos = nx.spring_layout(G)
plt.figure()    
nx.draw(G,pos,edge_color='black',width=1,linewidths=1,\
node_size=500,node_color='pink',alpha=0.9,\
labels={node:node for node in G.nodes()})
nx.draw_networkx_edge_labels(G,pos,edge_labels={('A','B'):'AB',\
('B','C'):'BC',('B','D'):'BD'},font_color='red')
plt.axis('off')
plt.show()

edge label