python教程-使用networkx画图简介

networkx 是一个使Python语言开发的图论与复杂网络建模工具,内置了非常多的常用的图与复杂网络分析算法,可以方便的帮助我们进行复杂网络数据分析、仿真建模等工作。

后续将陆续介绍networkx使用方法。

# pip install networkx

创建一个简单图

import networkx as nx
import matplotlib.pyplot as plt
#更新全局参数,设置图形大小
plt.rcParams.update({
    'figure.figsize':(8,6)
})


# 创建空的无向图
G = nx.Graph() 
G.add_node('Node1') # 一次添加一个节点(这里使用字母作为节点的id)
G.add_nodes_from(['Node2','Node3','Node4']) # 添加多个节点
# 添加一条线,连接Node1和Node2,
G.add_edge('Node1','Node2') 
# 同时添加多条线 
G.add_edges_from([('Node2','Node3'),('Node2','Node4'),('Node4','Node3')]) 
G.add_edges_from([('Node3', 'X'), ('Node2', 'T')])
nx.draw_networkx(G)
plt.show()
G = nx.karate_club_graph()
kara_pos = nx.spring_layout(G,k = 0.5) 
plt.figure()
nx.draw_networkx(G,kara_pos)
plt.show()
无向图

星状图

G = nx.star_graph(30)
pos = nx.spring_layout(G)
colors = range(30)
options = {
    "node_color": "#A0CBE2",
    "edge_color": colors,
    "width": 2,
    "edge_cmap": plt.cm.Blues,
    "with_labels": False,
nx.draw(G, pos, **options)
plt.show()
星状图


随机几何图

G = nx.random_geometric_graph(200, 0.125)
# position is stored as node attribute data for random_geometric_graph
pos = nx.get_node_attributes(G, "pos")
# find node near center (0.5,0.5)
dmin = 1
ncenter = 0
for n in pos:
    x, y = pos[n]
    d = (x - 0.5) ** 2 + (y - 0.5) ** 2
    if d < dmin:
        ncenter = n
        dmin = d
# color by path length from node near center
p = dict(nx.single_source_shortest_path_length(G, ncenter))
plt.figure(figsize=(8, 8))
nx.draw_networkx_edges(G, pos, nodelist=[ncenter], alpha=0.4)
nx.draw_networkx_nodes(
    nodelist=list(p.keys()),
    node_size=80,
    node_color=list(p.values()),
    cmap=plt.cm.Reds_r,