简体   繁体   中英

How to plot a subset of nodes of a networkx graph

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?

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)

在此处输入图像描述

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM