[英]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 在“元素 1”、“元素 2”中,但不在“元素 3”中,因为它有 1、1 和 0。
B 是“元素 1”、“元素 2”和“元素 3”,因为所有值都是 1 等等。最后一个值是该子列表中 0 和 1 的总和。
我创建了一个熊猫数据框来将它保存到一个 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
和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
这使:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.