Python案例如何用Networkx做图可视化

wen python案例 1

本文目录导读:

Python案例如何用Networkx做图可视化

  1. 安装所需库
  2. 基础图可视化
  3. 复杂图可视化案例
  4. 高级可视化技巧
  5. 交互式可视化
  6. 实用技巧

我来详细介绍如何使用NetworkX进行图可视化,包括多个实用案例。

安装所需库

pip install networkx matplotlib numpy

基础图可视化

简单无向图

import networkx as nx
import matplotlib.pyplot as plt
# 创建空图
G = nx.Graph()
# 添加节点
G.add_nodes_from([1, 2, 3, 4, 5])
# 添加边
G.add_edges_from([(1, 2), (1, 3), (2, 3), (3, 4), (4, 5)])
# 绘制图
plt.figure(figsize=(8, 6))
nx.draw(G, with_labels=True, node_color='lightblue', 
        node_size=500, font_size=16, font_weight='bold')"Simple Undirected Graph")
plt.show()

有向图

# 创建有向图
DG = nx.DiGraph()
# 添加边(自动添加节点)
DG.add_edges_from([(1, 2), (2, 3), (3, 1), (3, 4), (4, 2)])
plt.figure(figsize=(8, 6))
pos = nx.spring_layout(DG)  # 布局算法
nx.draw(DG, pos, with_labels=True, node_color='lightgreen',
        node_size=500, font_size=14, 
        arrows=True, arrowsize=20)"Directed Graph")
plt.show()

复杂图可视化案例

社交网络图

import networkx as nx
import matplotlib.pyplot as plt
import numpy as np
# 创建社交网络
G = nx.karate_club_graph()
plt.figure(figsize=(12, 8))
# 使用不同布局
pos = nx.spring_layout(G, k=0.5, iterations=50)
# 根据度数设置节点大小
node_sizes = [G.degree(node) * 100 for node in G.nodes()]
# 根据度数设置节点颜色
node_colors = [G.degree(node) for node in G.nodes()]
# 绘制
nx.draw(G, pos, 
        with_labels=True,
        node_size=node_sizes,
        node_color=node_colors,
        cmap=plt.cm.Reds,
        edge_color='gray',
        font_size=10,
        font_weight='bold')
"Karate Club Social Network")
plt.colorbar(plt.cm.ScalarMappable(cmap=plt.cm.Reds), 
             label='Node Degree')
plt.show()

流程图可视化

import networkx as nx
import matplotlib.pyplot as plt
# 创建流程图
G = nx.DiGraph()
# 添加节点和边
G.add_edge("开始", "数据输入")
G.add_edge("数据输入", "数据处理")
G.add_edge("数据处理", "数据验证")
G.add_edge("数据验证", "是否有效?")
G.add_edge("是否有效?", "数据存储")
G.add_edge("是否有效?", "错误处理")
G.add_edge("错误处理", "数据输入")
G.add_edge("数据存储", "结果输出")
G.add_edge("结果输出", "结束")
plt.figure(figsize=(12, 8))
# 自定义布局
pos = nx.spring_layout(G, k=3, iterations=200)
# 自定义节点样式
node_colors = []
node_shapes = []
for node in G.nodes():
    if node in ["开始", "结束"]:
        node_colors.append('lightgreen')
    elif node in ["是否有效?"]:
        node_colors.append('yellow')
    else:
        node_colors.append('lightblue')
# 绘制
nx.draw(G, pos, 
        with_labels=True,
        node_color=node_colors,
        node_size=3000,
        node_shape='s',
        font_size=12,
        font_weight='bold',
        edge_color='gray',
        arrows=True,
        arrowsize=20,
        width=2)
"Flow Chart Visualization")
plt.show()

高级可视化技巧

加权图(边权重可视化)

import networkx as nx
import matplotlib.pyplot as plt
import numpy as np
# 创建加权图
G = nx.Graph()
edges = [
    (1, 2, 0.3),
    (1, 3, 0.5),
    (2, 3, 0.1),
    (2, 4, 0.8),
    (3, 4, 0.6),
    (4, 5, 0.4)
]
G.add_weighted_edges_from(edges)
plt.figure(figsize=(10, 8))
pos = nx.spring_layout(G)
# 获取边权重
edge_weights = [G[u][v]['weight'] for u, v in G.edges()]
# 绘制节点
nx.draw_networkx_nodes(G, pos, node_color='lightcoral', 
                      node_size=500)
# 绘制标签
nx.draw_networkx_labels(G, pos, font_size=12, font_weight='bold')
# 绘制边(权重影响宽度)
nx.draw_networkx_edges(G, pos, 
                      width=np.array(edge_weights) * 5,
                      edge_color=edge_weights,
                      edge_cmap=plt.cm.Blues)
# 添加权重标签
edge_labels = nx.get_edge_attributes(G, 'weight')
nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels)
"Weighted Graph Visualization")
plt.axis('off')
plt.show()

多图组合

import networkx as nx
import matplotlib.pyplot as plt
# 创建多个子图
fig, axes = plt.subplots(2, 2, figsize=(15, 12))
# 1. 圆形布局
G1 = nx.cycle_graph(8)
pos1 = nx.circular_layout(G1)
nx.draw(G1, pos1, ax=axes[0,0], with_labels=True, 
        node_color='skyblue', node_size=300)
axes[0,0].set_title("Circular Layout")
# 2. 树形布局
G2 = nx.balanced_tree(3, 3)
pos2 = nx.spring_layout(G2, k=0.3, iterations=50)
nx.draw(G2, pos2, ax=axes[0,1], with_labels=True,
        node_color='lightgreen', node_size=300)
axes[0,1].set_title("Tree Layout")
# 3. 随机图
G3 = nx.erdos_renyi_graph(20, 0.2)
pos3 = nx.spring_layout(G3, k=1, iterations=100)
nx.draw(G3, pos3, ax=axes[1,0], with_labels=True,
        node_color='lightsalmon', node_size=200)
axes[1,0].set_title("Random Graph")
# 4. 网格图
G4 = nx.grid_2d_graph(4, 4)
pos4 = nx.spring_layout(G4, k=1, iterations=100)
nx.draw(G4, pos4, ax=axes[1,1], with_labels=True,
        node_color='lightpink', node_size=300)
axes[1,1].set_title("Grid Graph")
plt.tight_layout()
plt.show()

交互式可视化

使用plotly(需要安装)

# pip install plotly
import networkx as nx
import plotly.graph_objects as go
# 创建图
G = nx.karate_club_graph()
# 获取布局
pos = nx.spring_layout(G, k=0.5, iterations=50)
# 创建边迹
edge_trace = go.Scatter(
    x=[],
    y=[],
    line=dict(width=0.5, color='#888'),
    hoverinfo='none',
    mode='lines'
)
for edge in G.edges():
    x0, y0 = pos[edge[0]]
    x1, y1 = pos[edge[1]]
    edge_trace['x'] += tuple([x0, x1, None])
    edge_trace['y'] += tuple([y0, y1, None])
# 创建节点迹
node_trace = go.Scatter(
    x=[],
    y=[],
    mode='markers+text',
    hoverinfo='text',
    marker=dict(
        showscale=True,
        colorscale='YlGnBu',
        size=10,
        colorbar=dict(thickness=15)
    ),
    text=[str(node) for node in G.nodes()],
    textposition="bottom center"
)
for node in G.nodes():
    x, y = pos[node]
    node_trace['x'] += tuple([x])
    node_trace['y'] += tuple([y])
# 创建图表
fig = go.Figure(data=[edge_trace, node_trace],
                layout=go.Layout(
                    title='Interactive Network Graph',
                    showlegend=False,
                    hovermode='closest',
                    xaxis=dict(showgrid=False, zeroline=False),
                    yaxis=dict(showgrid=False, zeroline=False)
                ))
fig.show()

实用技巧

保存高质量图像

# 保存为不同格式
plt.savefig('graph.png', dpi=300, bbox_inches='tight')
plt.savefig('graph.pdf', format='pdf', bbox_inches='tight')
plt.savefig('graph.svg', format='svg', bbox_inches='tight')

自定义节点样式

def custom_graph_style():
    G = nx.karate_club_graph()
    pos = nx.spring_layout(G)
    plt.figure(figsize=(12, 8))
    # 自定义节点颜色和大小
    colors = ['red', 'blue', 'green', 'yellow', 'purple']
    node_colors = [colors[i % len(colors)] for i in range(len(G))]
    # 自定义边样式
    nx.draw_networkx_edges(G, pos, alpha=0.3, edge_color='gray')
    # 自定义节点
    nx.draw_networkx_nodes(G, pos, 
                          node_color=node_colors,
                          node_size=[d * 100 for d in dict(G.degree()).values()],
                          edgecolors='black',
                          linewidths=2)
    # 自定义标签
    nx.draw_networkx_labels(G, pos, font_size=8, font_weight='bold')
    plt.axis('off')
    plt.tight_layout()
    plt.show()
custom_graph_style()

这些案例展示了NetworkX进行图可视化的各种方法,根据你的具体需求选择合适的方式,可以创建出既美观又有信息量的图可视化。

抱歉,评论功能暂时关闭!