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.

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

    • for 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记录布局数据后可以复用位置信息。

   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   

 

posted on 2024-07-07 09:20  海阔凭鱼跃越  阅读(2)  评论(0编辑  收藏  举报