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()
二. 通过连接表和邻接表创建图
可以通过导入三元组连接表构建图。
也可以把图保存成邻接表,再读取。
代码举例:
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)
三. 从零开始创建图
任何可哈希的对象都可以作为图的节点。如:图、文件、字符串。
代码举例:
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()