使用 networkx 从大型 pandas 数据帧绘制网络

Plot network from large pandas dataframe using networkx

我正在 jupyter 上编写一个用于网络统计验证的程序,最终产品是一个大型 pandas 数据帧 5053x5053:

import pandas as pd
network = pd.DataFrame (data = app, index = products, columns = products)

app 是一个二进制矩阵,如果 app[i,j] = 1,则产品 i 链接到产品 j。我想绘制网络,我刚刚了解到可以使用 networkx(有时还有其他工具,如 cytoscape)。由于数据量很大,我不知道如何进行。哪种表示形式最好,我怎样才能获得可读的情节?我试图写下一些基本代码,但结果很令人失望:

import networkx as nx
import matplotlib.pyplot as plt

G = nx.Graph()
G = nx.from_pandas_edgelist(network)
nx.draw_random(G)

此外,我有一个包含 212 个绿色产品序列号(数据框的索引和列)的向量,如果可能的话,我想在同一个图上绘制不同的颜色。

编辑:我使用了代码,它比我尝试的效果更好,但它仍然不是一个可读的图表。

G = nx.from_numpy_matrix(gg)
G = nx.relabel_nodes(graph, dict(enumerate(greenxgreen.columns)))
nx.draw(G)

解决方案

我使用了下面虚拟数据部分的数据框(df)。这会给你一个基本的网络图。我鼓励您在文档中进一步挖掘(参见 参考资料 部分)。

nx.draw_random()创建随机排列。你有很多节点。所以它会造成混乱。您可能希望 select 数据帧的一个子集至少具有一定数量的连接并绘制它们以减少混乱。

# G = graph
G = nx.from_numpy_matrix(df.values)
G = nx.relabel_nodes(G, dict(enumerate(df.columns)))
# nx.draw_spectral(G)
# nx.draw_random(G)
# nx.draw_circular(G)
nx.draw(G)

要绘制整个网络,包括标签、边等,请使用nx.draw_networkx()

nx.draw_networkx(G)

虚拟数据

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

import networkx as nx

%matplotlib inline

## To randomly generate array: a
#  Uncomment the following three lines
# seed = 0
# np.random.seed(seed=seed)
# a = (np.random.rand(25).reshape(5,5) >= 0.5).astype(int)

## To use a fixed representation of array: a
a = np.array([
    [1, 1, 1, 1, 0],
    [1, 0, 1, 1, 0],
    [1, 1, 1, 1, 0],
    [0, 0, 1, 1, 1],
    [1, 1, 0, 1, 0]
    ])

nodes = list('ABCDE')
df = pd.DataFrame(data=a, index=nodes, columns=nodes)
print(df)

参考资料

  1. Construct NetworkX graph from Pandas DataFrame
  2. Documentation: networkx.convert_matrix.from_pandas_dataframe
  3. Documentation: networkx.convert_matrix.from_pandas_edgelist