始める無料で始める

サブグラフ I

ネットワークの一部のノードだけを分析したいことがあります。その場合は、G.subgraph(nodes) を使って別のグラフオブジェクトにコピーできます。これは、渡した nodes(反復可能オブジェクト)から構成される新しい graph オブジェクト(元のグラフと同じ型)を返します。

matplotlib.pyplotplt としてインポート済みです。

この演習はコースの一部です

Pythonで学ぶネットワーク分析入門

コースを見る

演習の手順

  • グラフ G から、nodes_of_interest とそれらの近傍ノードで構成されるサブグラフを抽出する関数 get_nodes_and_nbrs(G, nodes_of_interest) を作成します。
    • 最初の for ループでは、nodes_of_interest を反復し、現在のノード nnodes_to_draw に追加します。
    • 2つ目の for ループでは、n の近傍ノードを反復し、すべての近傍ノード nbrnodes_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()
コードを編集して実行