pythonrpandasnetworkxsubcomponent

Networkx: Plot a subgraph similar to subcomponent in igraph R


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.


Solution

  • 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