简体   繁体   English

从加权边缘列表创建有向加权网络图

[英]Creating a directed, weighted network graph from weighted edgelist

I have the following edgelist which is stored in edgelist.txt :我有以下 edgelist 存储在edgelist.txt中:

soldier1, soldier2, 3
soldier1, soldier3, 1
soldier1, soldier4, 2
soldier2, soldier1, 2
soldier2, soldier3, 1
soldier2, soldier4, 3
soldier3, soldier1, 3
soldier3, soldier2, 2
soldier3, soldier4, 1
soldier4, soldier1, 2
soldier4, soldier2, 1
soldier4, soldier3, 3

To draw the graph, I'm using the following code:为了绘制图表,我使用以下代码:

import networkx as nx
import matplotlib.pyplot as plt

G = nx.read_weighted_edgelist(path='edgelist.txt', delimiter=',', create_using=nx.DiGraph())
nx.draw_networkx(G, with_labels=True, arrowsize=5, pos=nx.spring_layout(G))
limits=plt.axis('off')
plt.show()

However, it is creating a graph with double the amount of nodes (there should only be 4, but it is creating the graph with 8.) This is evident when you view the plot of the graph:但是,它正在创建一个具有双倍节点数量的图形(应该只有 4 个,但它正在创建具有 8 个的图形。)当您查看图形的 plot 时,这一点很明显: 网络图

Here is the graph info:这是图表信息:

Name: 
Type: DiGraph
Number of nodes: 8
Number of edges: 12
Average in degree:   1.5000
Average out degree:   1.5000

The number of edges is correct but there are double the nodes.边数是正确的,但节点数是双倍的。 How do I fix this?我该如何解决?

Since you specify , as a delimiter, the whitespace character is considered part of the name.由于您指定,作为分隔符,因此空白字符被视为名称的一部分。
So you'll end up with two nodes ' soldierN' and 'soldierN' for each node.因此,每个节点都会有两个节点' soldierN''soldierN'

You can change your delimiter to consider also the whitespace, ie, from ',' to ', '您可以更改分隔符以考虑空格,即从','', '

>>> G = nx.read_weighted_edgelist(path='edgelist.txt', delimiter=', ', create_using=nx.DiGraph())
>>> G.nodes()
['soldier1', 'soldier2', 'soldier3', 'soldier4']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM