How to plot a subset of nodes of a networkx graph

Viewed 2280

This is code similar to my code

import networkx as nx
from matplotlib import pyplot as plt
%matplotlib notebook
import pandas as pd

data={"A":["T1","T2","tom","adi","matan","tali","pimpunzu","jack","arzu"],
      "B":["end","end","T1","T1","T1","T2","T2","matan","matan"]}

df=pd.DataFrame.from_dict(data)

G = nx.from_pandas_edgelist(df,source='A',target='B', edge_attr=None, create_using=nx.DiGraph())
f, ax = plt.subplots(figsize=(10, 10))
nx.draw(G, with_labels=True, font_weight='bold', ax=ax)

i like to plot part of the graph for example ,i like to plot just ["T1","matan","jack","arzu"]

that what i like to get

data={"A":["jack","arzu","matan"],
      "B":["matan","matan","T1"]}

df=pd.DataFrame.from_dict(data)

G = nx.from_pandas_edgelist(df,source='A',target='B', edge_attr=None, create_using=nx.DiGraph())
f, ax = plt.subplots(figsize=(10, 10))
nx.draw(G, with_labels=True, font_weight='bold', ax=ax)

can i put list of what i like to plot? or maybe can i write the nodes i like to plot between them?

2 Answers

You can generate a nx.subgraph from a list of nodes, and draw as you're doing above:

H = nx.subgraph(G, ["T1","matan","jack","arzu"])
nx.draw(H, with_labels=True, font_weight='bold', node_color='lightblue', node_size=500)

enter image description here

You are trying to plot a subgraph of your original graph. To do this, you can use the networkx.Graph.subgraph method:

import networkx as nx
import pandas as pd

# Build a graph using a pd.DataFrame
data = {"A": ["T1","T2","tom","adi","matan","tali","pimpunzu","jack","arzu"],
        "B": ["end","end","T1","T1","T1","T2","T2","matan","matan"]}
df = pd.DataFrame.from_dict(data)
G = nx.from_pandas_edgelist(df, source='A', target='B', edge_attr=None,
                            create_using=nx.DiGraph())

# Build subgraph containing a subset of the nodes, and edges between those nodes
subgraph = G.subgraph(["T1","matan","jack","arzu"])

Now you just need to simply plot your new graph using the same function from matplotlib you have already used.

Related