问题
I'm reading an edgelist using networkX. The edgelist contains entries of the form:
1; 2; 3
2; 3; 5
3; 1; 4
where 3rd column is the weight. When I plot this, it displays the weight 3 as:
{'weight': 3}
instead of just 3. Ultimately I want to be able to perform operations using the weight (e.g. calculated highest weight, display only the edges which have a weight:
'x', etc.,
Here is the minimal working code:
import networkx as nx
import pylab as plt
G=nx.Graph()
G=nx.read_edgelist('sample_with_weights.edges', data= (('weight',int),))
pos = nx.spring_layout(G)
nx.draw_networkx(G, pos=pos)
nx.draw_networkx_edge_labels(G, pos=pos)
nx.draw_networkx_edges(G,pos,width=4, edge_color='g', edge_labels = 'weight', arrows=False)
plt.show()
回答1:
Some observations regarding the existing code:
That
read_edgelist
is not going to work well with that edge list file because the 'special' delimiter;
has not been specified.The edge labels should be specified in the
draw_networkx_edge_labels
function call, rather than thedraw_networkx_edges
; and alsoThe
edge_labels
is a dictionary keyed by edge two-tuple of text labels (default=None). Only labels for the keys in the dictionary are drawn. (from the documentation)
So, the general idea is to use the edge_labels
to selectively print edge weights. Please see inline comments below:
import networkx as nx
import pylab as plt
G=nx.Graph()
#Please note the use of the delimiter parameter below
G=nx.read_edgelist('test.edges', data= (('weight',int),), delimiter=";")
pos = nx.spring_layout(G)
#Here we go, essentially, build a dictionary where the key is tuple
#denoting an edge between two nodes and the value of it is the label for
#that edge. While constructing the dictionary, do some simple processing
#as well. In this case, just print the labels that have a weight less
#than or equal to 3. Variations to the way new_labels is constructed
#produce different results.
new_labels = dict(map(lambda x:((x[0],x[1]), str(x[2]['weight'] if x[2]['weight']<=3 else "") ), G.edges(data = True)))
nx.draw_networkx(G, pos=pos)
#Please note use of edge_labels below.
nx.draw_networkx_edge_labels(G, pos=pos, edge_labels = new_labels)
nx.draw_networkx_edges(G,pos,width=4, edge_color='g', arrows=False)
plt.show()
Given a data file test.edges
that looks like...
1;2;3
2;3;3
3;4;3
2;4;4
4;6;5
1;6;5
...the above snippet will produce a result similar to:
Hope this helps.
来源:https://stackoverflow.com/questions/31575634/problems-printing-weight-in-a-networkx-graph