python-graph-study2024-7

海阔凭鱼跃越發表於2024-07-07

1. 先打基礎

1 基礎學習筆記

Graph Creation

NetworkX graph objects can be created in one of three ways:

  • Graph generators—standard algorithms to create network topologies.

  • Importing data from preexisting (usually file) sources.

  • Adding edges and nodes explicitly.

Edge attributes can be anything:

import math
G.add_edge('y', 'x', function=math.cos)
G.add_node(math.cos)  # any hashable can be a node


已有生成演算法生成專門的圖

Graph generators such as binomial_graph() and erdos_renyi_graph() are provided in the graph generators subpackage.

從檔案讀入圖資料-寫圖資料到外部檔案

For importing network data from formats such as GML, GraphML, edge list text files see the reading and writing graphs subpackage.

 

Graph Reporting 和 Algorithms

Drawing

1 import matplotlib.pyplot as plt
2 G = nx.cubical_graph()
3 subax1 = plt.subplot(121)
4 nx.draw(G)   # default spring_layout
5 subax2 = plt.subplot(122)
6 nx.draw(G, pos=nx.circular_layout(G), node_color='r', edge_color='b')

Data Structure

NetworkX uses a “dictionary of dictionaries of dictionaries” as the basic network data structure. This allows fast lookup with reasonable storage for large sparse networks. The keys are nodes so G[u] returns an adjacency dictionary keyed by neighbor to the edge attribute dictionary. A view of the adjacency data structure is provided by the dict-like object G.adj as e.g. for node, nbrsdict in G.adj.items():. The expression G[u][v] returns the edge attribute dictionary itself. A dictionary of lists would have also been possible, but not allow fast edge detection nor convenient storage of edge data.

Advantages of dict-of-dicts-of-dicts data structure:

  • Find edges and remove edges with two dictionary look-ups.

  • Prefer to “lists” because of fast lookup with sparse storage.

  • Prefer to “sets” since data can be attached to edge.

    • G[u][v]   returns the edge attribute dictionary.

    • n in G    tests if node n is in graph G.

    • for n in G:   iterates through the graph.

    • for nbr in G[n]:   iterates through neighbors.

ego_graph

返回給定半徑內以節點n為中心的鄰居的誘導子圖。

2.關於佈局

1. 記錄已有的佈局資料——重複繪圖時使用上次的佈局

舉例:

draw_planar——用平面佈局畫一個平面網路圖G。

draw_planar(G, **kwargs)

This is a convenience function equivalent to:

nx.draw(G, pos=nx.planar_layout(G), **kwargs)


每次呼叫該函式時都會計算佈局。對於重複繪製,直接呼叫planar_layout並重用結果會更有效:

1 G = nx.path_graph(5)
2 pos = nx.planar_layout(G)
3 nx.draw(G, pos=pos)  # Draw the original graph
4 # Draw a subgraph, reusing the same node positions
5 nx.draw(G.subgraph([0, 1, 2]), pos=pos, node_color="red")

使用pos記錄佈局資料後可以複用位置資訊。