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.
Installing relevant packages is a prerequisite for use.
For the convenience of subsequent display, you may wish to set matplotlib to allow Chinese display.
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 inzip(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.
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.