サブグラフ I
ネットワークの一部のノードだけを分析したいことがあります。その場合は、G.subgraph(nodes) を使って別のグラフオブジェクトにコピーできます。これは、渡した nodes(反復可能オブジェクト)から構成される新しい graph オブジェクト(元のグラフと同じ型)を返します。
matplotlib.pyplot は plt としてインポート済みです。
この演習はコースの一部です
Pythonで学ぶネットワーク分析入門
演習の手順
- グラフ
Gから、nodes_of_interestとそれらの近傍ノードで構成されるサブグラフを抽出する関数get_nodes_and_nbrs(G, nodes_of_interest)を作成します。- 最初の
forループでは、nodes_of_interestを反復し、現在のノードnをnodes_to_drawに追加します。 - 2つ目の
forループでは、nの近傍ノードを反復し、すべての近傍ノードnbrをnodes_to_drawに追加します。
- 最初の
- 関数を使って、事前定義のリスト
nodes_of_interestに含まれるノード 29、38、42 とその近傍ノードで構成されるTのサブグラフを抽出し、結果をT_drawとして保存します。 - サブグラフ
T_drawを画面に描画します。
実践的なインタラクティブ演習
このサンプルコードを完成させて、この演習に挑戦してみましょう。
nodes_of_interest = [29, 38, 42]
# Define get_nodes_and_nbrs()
def get_nodes_and_nbrs(G, nodes_of_interest):
"""
Returns a subgraph of the graph `G` with only the `nodes_of_interest` and their neighbors.
"""
nodes_to_draw = []
# Iterate over the nodes of interest
for n in ____:
# Append the nodes of interest to nodes_to_draw
____
# Iterate over all the neighbors of node n
for nbr in ____:
# Append the neighbors of n to nodes_to_draw
____
return G.subgraph(nodes_to_draw)
# Extract the subgraph with the nodes of interest: T_draw
T_draw = ____
# Draw the subgraph to the screen
____
plt.show()