004NetworkX function introduction and inspiration


Zero. Preface

  1. When generative models are in the ascendant, writing code with the help of AI has become a good option. We can spare more time to learn new things. Therefore, this chapter only provides a functional introduction and inspiration for NetworkX. Not only that, but subsequent blogs will also carry on this idea.
  2. Installing relevant packages is a prerequisite for use.
  3. For the convenience of subsequent display, you may wish to set matplotlib to allow Chinese display.
  4. If you want to know the function of a certain NetworkX function, you can get help by adding a question mark.
nx.pagerank? # 获取帮助
nx.pagerank?? # 获取源码

1. Create the built-in graph of NetworkX

  • Simple structure diagram. Such as: fully connected undirected graph, fully connected directed graph, ring graph, tree structure graph, etc.
  • Social network diagram. Such as: karate club graph ( nx.karate_club_graph() ), character relationship graph of "Les Misérables", etc.
  • Code example:
import networkx as nx
import matplotlib.pyplot as plt

G = nx.karate_club_graph()

print(G.nodes[5]['club']) # 查看节点的属性特征

plt.figure(figsize=(12,10)) # 创建一个新的图形窗口,并设置其大小为宽度为12英寸、高度为10英寸
pos = nx.spring_layout(G, seed=10) # 生成节点布局,此处用弹性布局,也可以指定节点坐标
nx.draw(G, pos=pos, with_labels=True)
plt.show()
import networkx as nx
import matplotlib.pyplot as plt

tree = nx.random_tree(n=10,seed=0)

print(nx.forest_str(tree, sources=[0]))

nx.draw(tree)
plt.show()

2. Create graphs through join tables and adjacency lists

  • Graphs can be constructed by importing triple join tables.
  • You can also save the graph as an adjacency list and read it later.
  • Code example:
import pandas as pd
import networkx as nx
import matplotlib.pyplot as plt

df = pd.read_csv('T1.csv') # 导入三元组连接表,用于构建有向图

G = nx.DiGraph() # 构建空的有向图

# 根据三元组连接表添加节点与连接
edges = [edge for edge in zip(df['head'], df['tail'])]
G.add_edges_from(edges)

print(G.edges('shen')) # 查看节点的全部连接

pos = nx.spring_layout(G, seed=10)
plt.figure(figsize=(15,15))
nx.draw(G, pos, with_labels=True)
plt.show()

# 展示邻接表
for line in nx.generate_adjlist(G):
    print(line)

# 保存邻接表
nx.write_edgelist(G, path='grid.edgelist', delimiter=':')

# 读取邻接表
H = nx.read_edgelist(path='grid.edgelist', delimiter=':')

print(H)

3. Create a diagram from scratch

  • Any hashable object can serve as a node of the graph. Such as: pictures, files, strings.
  • Code example:
import networkx as nx
import matplotlib.pyplot as plt

G = nx.Graph() # 创建空无向图

# 给图添加属性特征
G.graph['name'] = 'HelloWorld'

"""添加节点"""
# 逐个添加节点
G.add_node('chen')
G.add_node('shen')
G.add_node(1)
G.add_node(0,fea1=5, fea2=10)

# 批量添加节点
G.add_nodes_from(['yang', 'zhao'])
G.add_nodes_from(range(100,105))

# 批量添加带属性特征的节点
G.add_nodes_from([
    ('sun',{
    
    'id':154004,'class':'002'}),
    ('zhang',{
    
    'id':157004,'class':'001'}),
    ('li',{
    
    'id':157984,'class':'004'})
])

# 创建一个新图,把新图的各节点与新图本身加到旧图里
H = nx.path_graph(10)
G.add_nodes_from(H) # 注:同名节点会被合并
G.add_node(H) # 把图当成一个节点传入

"""添加连接"""
G.add_edge(1, 'chen', weight=0.5)
G.add_edges_from([
    ('chen', 'shen', {
    
    'weight':0.8}),
    (0, 101, {
    
    'weight':0.9})
])

print(G.graph)
print(G.nodes)
print(G.nodes(data=True))
print(G.nodes[0])
print(G.nodes['li']['id'])
print(G.edges[[0,101]])
print(G.degree[101])
print(G.neighbors('chen'))

nx.draw(G, with_labels=True)
plt.show()

4. nx.draw() visual customization

  • Use nx.draw() to draw different styles of diagrams.
  • It can set node size, node color, node outline color, node coordinates, connection color, link thickness, arrow size, whether to display node labels, etc.
  • You can specify them one by one or use a dictionary.
  • Richer drawing styles can be achieved by drawing nodes and edges in batches.
nx.draw_networkx_nodes(G, pos, node_size=30, nodelist=['chen',1,101,'zhao'], node_color='blue')
nx.draw_networkx_nodes(G, pos, node_size=15, nodelist=['yang'], node_color='red')
nx.draw_networkx_edges(G, pos, alpha=0.5, width=6)
import networkx as nx
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors

def draw(G, pos, measures, measure_name):
    nodes = nx.draw_networkx_nodes(G, pos, node_size=250, cmap=plt.cm.plasma,
                                   node_color=list(measures.values()),
                                   nodelist=measures.keys())
    nodes.set_norm(mcolors.SymLogNorm(linthresh=0.01,linscale=1,base=10))
    edges = nx.draw_networkx_edges(G, pos)

    plt.title(measure_name)
    plt.colorbar(nodes)
    plt.axis('off')
    plt.show()

G = nx.karate_club_graph()

pos = nx.spring_layout(G, seed=10)
draw(G, pos, nx.betweenness_centrality(G), 'Node Degree')
draw(G, pos, dict(G.degree), 'Node Degree')

5. Other pictures

  • Multi-way connection graph: G = nx.from_pandas_edgelist(df, 'White', Black', edge_attr=True, create_using=nx.MultiDiGraph())
  • Egocentric graph (Ego graph): Find the main node with the largest number of connections and construct a neighborhood subgraph centered on it.
  • Graph of custom node icons

6. Common image operations

  • The following operations can be printed using print, and basically they can also be traversed using a for loop:
  • Determine whether it is a directed graph: G.is_directed()
  • View the number of nodes and connections in the graph: G
  • View the number of nodes in the graph: G.number_of_nodes()
  • View the number of connections in the entire graph: G.number_of_edges()
  • View all nodes: G.nodes
  • View all nodes and their attribute characteristics: G.nodes(data=True)
  • View all edges: G.edges
  • View all edges and their attribute characteristics: G.edges(data=True)
  • View the attribute characteristics of the graph: G.graph
  • View node attribute characteristics: G.nodes[node name/number]
  • View node attribute characteristic values: G.nodes[node name/number][characteristic name]
  • View all connections of a node: G.edges (node ​​name)
  • View connection characteristics: G.edges[[node pairs]]
  • View the degree of a node: G.degree[node name]
  • View the neighboring nodes of a node: G.neighbors (node ​​name), return a dictionary.

おすすめ

転載: blog.csdn.net/qq_44928822/article/details/132718449