1
votes

I have a file with lines like these (node1; node2; label-weight)

497014; 5674; 200
5674; 5831; 400
410912; 5674; 68,5
7481; 5674; 150
5831; 5674; 200

the first and the second elements in the row are nodes of a networkx graph. The third is the edge's label (or weight or lenght). I'm using python 3.4 and networkx 1.9 and I would like to plot labels near or inside the edges (it would be nice if the weight = label = thickness of the edge)

with this code, plotted edges don't have labels.

import networkx as nx
import matplotlib.pyplot as plt
data= open("C:\\Users\\User\\Desktop\\test.csv", "r")
G = nx.DiGraph()

for line in data:
    (node1, node2, weight1) = (line.strip()).split(";")
    G.add_edge(node1, node2, label=str(weight1),length=int(weight1))

nx.draw_networkx(G)
plt.show()

I've seen that is possible to add edges with labels using dictionaries. I'm working on that but at the moment this solution is too far from me.

Thanks.

1

1 Answers

2
votes

You are definitely on the right track, but there are a few issues with your code.

  1. Your example file has spaces after the semicolon, so you should split on those spaces, too.

    node1, node2, weight1 = line.strip().split("; ")
    
  2. Your weights appear to be floats rather than ints (as in your example), so you need to replace the "," in your weights with ".". (An alternative would be to check out the locale module.)

    weight1 = weight1.replace(",", ".")
    
  3. To create the dictionary for edge labels, all you need to do is map each edge (pair of nodes) to its label, like so:

    edge_labels[(node1, node2)] = float(weight1)
    

    Then you can call draw_networkx_edge_labels to plot the edge labels with the rest of your graph:

    pos = nx.spring_layout(G)
    nx.draw_networkx(G, pos=pos)
    nx.draw_networkx_edge_labels(G, pos=pos, edge_labels=edge_labels)
    

Putting it all together, here's all the code you need

import networkx as nx
import matplotlib.pyplot as plt

data= open("test.txt", "r") # replace with the path to your edge file
G = nx.DiGraph()
edge_labels = dict()
for line in data:
    node1, node2, weight1 = line.strip().split("; ")
    length = float(weight1.replace(",", ".")) # the length should be a float
    G.add_edge(node1, node2, label=str(weight1), length=length)
    edge_labels[(node1, node2)] = weight1 # store the string version as a label

# Draw the graph
pos = nx.spring_layout(G) # set the positions of the nodes/edges/labels
nx.draw_networkx(G, pos=pos) # draw everything but the edge labels
nx.draw_networkx_edge_labels(G, pos=pos, edge_labels=edge_labels)
plt.show()

And here's your output graph:

output graph with weighted edge labels