Networkx 没有 return 来自邻接矩阵的漂亮图

Networkx does not return a nice graph from adjacency matrix

我有一个矩阵如下:

adjacency_matrix = [['A', 1, 1, 0, 2], ['B', 1, 1, 1, 3], ['C', 0, 0, 1, 1]]

它表明 A 在 "Element 1"、"Element 2" 但不在 "Element 3",因为它有 1、1 和 0。

B 是 "Element 1"、"Element 2" 和 "Element 3",因为所有值都是 1 等等。最后一个值是该子列表中 0 和 1 的总和。

我创建了一个 pandas 数据框来将其保存到 csv 文件中。在保存之前,它按总和对其进行排序,然后删除最后一列(总和)。

df = pd.DataFrame(adjacency_matrix, columns = ["Name", "Element 1", "Element 2", "Element 3", "Sum"])
df = df.sort_values(by=['Sum'], ascending=False)
df = df.iloc[:, :-1]

我的下一步是使用邻接矩阵并创建一个漂亮的连接图。

G=from_pandas_edgelist(df, source="Name", target=["Name", "Element 1", "Element 2", "Element 3"])
nx.draw_circular(G, with_labels=True)
plt.axis('equal')
plt.show()

我做错了什么?我没有得到 "A" 连接到元素 1 和元素 2 的无向图。我感觉我的源和目标是错误的。

将邻接矩阵重组为边列表。这是一个使用 DataFrame.melt and DataFrame.query:

的例子
df = pd.DataFrame(adjacency_matrix, columns = ["Name", "Element 1", "Element 2", "Element 3", "Sum"])
df = df.sort_values(by=['Sum'], ascending=False)
df = df.iloc[:, :-1]

df_edges = (df.melt(id_vars='Name', var_name='target')
            .query('value==1'))

[出局]

  Name     target  value
0    A  Element 1      1
1    B  Element 1      1
3    A  Element 2      1
4    B  Element 2      1
7    B  Element 3      1
8    C  Element 3      1


G = nx.from_pandas_edgelist(df_edges, source='Name', target='target')
nx.draw_networkx(G)

我的方法是重组您的 adjacency_matrix 以包括所有对:

adjacency_matrix = [['A', 1, 1, 0, 2], ['B', 1, 1, 1, 3], ['C', 0, 0, 1, 1]]

df = pd.DataFrame(adjacency_matrix, columns = ["Name", "Element 1", "Element 2", "Element 3", "Sum"])
df = df.sort_values(by=['Sum'], ascending=False)
df = df.iloc[:, :-1]

df = df.set_index('Name')

edges = df.columns

for i in df.index:
    df[i] = [0 for _ in range(len(df.index))]

for e in edges:
    r = [0 for _ in range(len(df.columns))]
    df.loc[len(df)] = r


as_list = df.index.tolist()
as_list[len(adjacency_matrix):] = edges
df.index = as_list


G=nx.from_pandas_adjacency(df)
nx.draw_circular(G, with_labels=True)
plt.axis('equal')
plt.show()

使你的df如下:

           Element 1  Element 2  Element 3  B  A  C
B                  1          1          1  0  0  0
A                  1          1          0  0  0  0
C                  0          0          1  0  0  0
Element 1          0          0          0  0  0  0
Element 2          0          0          0  0  0  0
Element 3          0          0          0  0  0  0

给出: