Networkx:绘制类似于 igraph R 中的子组件的子图

Networkx: Plot a subgraph similar to subcomponent in igraph R

我正在尝试在 Python 上绘制 networkx 图。我不想绘制所有节点和边,而是想过滤掉对用户给定节点具有 link 的节点。我认为这类似于 R 中 iGraph 中的子组件。 例如,在下面的代码中,我的数据框有一个节点 4429。我想绘制直接或间接连接到 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() 

如有任何帮助,我们将不胜感激。 谢谢。

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

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)

this是您要找的吗?

编辑:不确定为什么这会被否决,但我认为这确实是答案。这是一个例子:

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()

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

subs = nx.connected_component_subgraphs(G)
seed = 4429
g = [sg for sg in subs if seed in sg][0]
nx.draw_networkx(g)