0

I'm trying to plot a networkx graph on Python. Instead of plotting all nodes and edges, I'd like to filter out nodes which has link to a user given node. I think this is similar to subcomponent in iGraph in R. For example, in the below code, my dataframe has a node 4429. I'd like to plot nodes and edges that are connected directly or indirectly to 4429.

import networkx as nx
import numpy as np
import matplotlib.pyplot as plt
import pylab

G = nx.DiGraph()

g = nx.from_pandas_edgelist(dataframe, 'Source', 'Target', ['Freq'])
nx.draw_networkx(g)
plt.xticks([], [])
plt.yticks([], [])
fig = plt.gcf()
fig.set_size_inches(15, 15)

plt.show() 

Any help would be appreciated. Thanks.

4

3 回答 3

2

这是要找的吗?

编辑:不知道为什么这被否决了,但我认为这就是答案。这是一个例子:

import networkx as nx
from matplotlib.pyplot import subplots
G = nx.path_graph(4)
G.add_edge(5,6)

fig, ax = subplots(2)
for axi, sub in zip(ax, nx.connected_component_subgraphs(G)):
    nx.draw(sub, ax = axi)

在此处输入图像描述

编辑 2:仅对于连接到节点的子网使用:

import networkx as nx
from matplotlib.pyplot import subplots
G = nx.path_graph(4)
G.add_edge(5,6)

fig, ax = subplots()
subnet = nx.node_connected_component(G, 0)
nx.draw(G.subgraph(subnet), ax = ax, with_labels = True)
fig.show()

在此处输入图像描述

于 2018-11-01T22:09:17.407 回答
0

一个快速的解决方案可能是过滤数据框:

g = nx.from_pandas_edgelist(dataframe.loc[(dataframe["Source"] == id) | (dataframe["Target"] == id)])

如果您知道可以使用的最大度数single_source_dijkstra_path_length

nx.single_source_dijkstra_path_length(G=graph,
                                      Source=id,
                                      cutoff=cutoff)
于 2018-11-01T21:56:24.263 回答
0

在所有连接的组件中,找到包含相关节点的组件,并绘制它。

subs = nx.connected_component_subgraphs(G)
seed = 4429
g = [sg for sg in subs if seed in sg][0]
nx.draw_networkx(g)
于 2018-11-01T22:20:55.583 回答