Build a graph with edges' lengths displayed using distance matrix
假设我有一个csv('matrix.csv')文件,其中包含图形的边长对称矩阵:
1 2 3 4 5 | ,a,b,c,d a,nan,0.3,0.2,nan b,0.3,nan,nan,nan c,0.2,nan,nan,0.1 d,nan,nan,0.1,nan |
作为输出,我想得到一张图形的图片,其中有3条边,将a与b,a与c和d与c连接,并在这些边上写出距离。
到目前为止,我有一个使用pandas dataframe对象将csv文件读入numpy对象的代码(我知道这很愚蠢,但是from_pandas_dataframe在networkx上不起作用)
1 2 3 4 5 6 7 8 9 10 11 12 13 | import matplotlib import networkx as nx matplotlib.use('TkAgg') import matplotlib.pyplot as plt import pandas as pd df = pd.read_csv('matrix.csv', sep=',',index_col=0, decimal=",") numpyMatrix = df.as_matrix() G1 = nx.from_numpy_matrix(numpyMatrix) G = nx.Graph(numpyMatrix) nx.draw(G, with_labels=True, pos=nx.spring_layout(G), node_color='salmon') plt.draw() plt.show() |
但是代码还绘制了所有其他边(" nan"值)。
另一个问题是,例如,如何仅绘制长度大于0.1的一组边?
在将数据帧转换为矩阵之前,可以使用Pandas .fillna()方法将nans替换为0。然后请注意,矩阵具有0和其他浮点数的字符串版本。然后,您可以使用numpy数组.astype()方法将矩阵条目的大小写设置为浮点型。
1 2 | numpyMatrix = df.fillna(0).as_matrix() numpyMatrix = numpyMatrix.astype(float) |
如果您想进一步过滤边缘,请查看:
在networkx中找到满足特定条件的边缘
回答问题的第二部分:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | import matplotlib import networkx as nx matplotlib.use('TkAgg') import matplotlib.pyplot as plt import pandas as pd df = pd.read_csv('mat.csv', sep=';',index_col=0, decimal=",") l = list(df) G = nx.Graph() for item in l: for item0 in l: if l.index(item0) < l.index(item) and df[item][item0] > 0.1: G.add_edge(item, item0, weight=df[item][item0]) nx.draw(G, with_labels=True, pos=nx.spring_layout(G), node_color='salmon') plt.draw() plt.show() |
基本上,在这里您读取了csv文件,然后(假设对称矩阵)对每对确定(不)在两个节点之间绘制边的节点(假设是对称矩阵)(如果是某个条件,则为df [item] [ item0]> 0.1,即边的长度(权重)大于0.1)。