Networkx: Plot a subgraph similar to subcomponent in igraph R

918 Views Asked by At

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.

3

There are 3 best solutions below

4
cvanelteren On BEST ANSWER

Is this what you are looking for?

Edit: not sure why this is downvoted but I think this is literally the answer. Here is an example:

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)

enter image description here

edit 2: for only the subnet connected to a node use this:

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

enter image description here

3
Alberto Bonsanto On

A fast solution could be filtering the dataframe:

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

If you know the maximum degree you can use single_source_dijkstra_path_length

nx.single_source_dijkstra_path_length(G=graph,
                                      Source=id,
                                      cutoff=cutoff)
2
DYZ On

Among all connected components, find the one that contains the node in question, and plot it.

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