在NetworkX图形中打印权重问题 [英] Problems printing weight in a NetworkX graph

查看:365
本文介绍了在NetworkX图形中打印权重问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用networkX阅读边缘列表.边缘列表包含以下形式的条目:

I'm reading an edgelist using networkX. The edgelist contains entries of the form:

1; 2; 3

2; 3; 5

3; 1; 4

其中第三列是重量.当我绘制此图形时,它将权重3显示为:

where 3rd column is the weight. When I plot this, it displays the weight 3 as:

{'weight': 3}

而不是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'等,

'x', etc.,

这是最小的工作代码:

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()

推荐答案

关于现有代码的一些观察结果:

Some observations regarding the existing code:

  1. 由于未指定特殊"定界符;,因此read_edgelist不能与该边缘列表文件一起很好地工作.

  1. That read_edgelist is not going to work well with that edge list file because the 'special' delimiter ; has not been specified.

应该在draw_networkx_edge_labels函数调用中指定边缘标签,而不是在draw_networkx_edges中指定;还有

The edge labels should be specified in the draw_networkx_edge_labels function call, rather than the draw_networkx_edges; and also

edge_labels由文本标签的边缘二元组(默认为无)键入的字典.仅绘制字典中键的标签.(摘自因此,通常的想法是使用edge_labels有选择地打印边缘权重.请查看下面的内嵌评论:

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()

给出一个看起来像...的数据文件test.edges

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:

希望这会有所帮助.

这篇关于在NetworkX图形中打印权重问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆