如何使用Python NetworkX复现流程图并适配CSV/Excel数据源
适配多数据源的NetworkX流程图实现方案
1. 通用数据源结构设计(支持Excel/CSV)
你只需要按固定规则准备两个数据表,存为同一Excel的两个工作表,或者两个独立的CSV文件即可:
- 节点表(工作表名/文件名前缀:nodes)
必选列:node_id(节点唯一标识,数字/字符串均可)、node_label(节点显示文本)
可选列:node_type(区分节点类型,取值可设为start/process/decision/end,用于匹配样式)、level(手动指定节点所在层级,控制布局顺序) - 边表(工作表名/文件名前缀:edges)
必选列:from_node(起点node_id)、to_node(终点node_id)
可选列:edge_label(边的显示文本,比如判断分支的"是""否")
2. 完整实现代码
先安装依赖:pip install pandas networkx matplotlib openpyxl
代码示例:
import pandas as pd import networkx as nx import matplotlib.pyplot as plt def build_flowchart(file_path, sheet_names=None): # 初始化有向流程图 G = nx.DiGraph() # 自动匹配文件格式读取 if file_path.endswith(('.xlsx', '.xls')): sheet_names = sheet_names or ['nodes', 'edges'] nodes_df = pd.read_excel(file_path, sheet_name=sheet_names[0]) edges_df = pd.read_excel(file_path, sheet_name=sheet_names[1]) elif file_path.endswith('.csv'): # CSV格式默认读取同目录下的{文件名}_nodes.csv和{文件名}_edges.csv nodes_df = pd.read_csv(file_path.replace('.csv', '_nodes.csv')) edges_df = pd.read_csv(file_path.replace('.csv', '_edges.csv')) else: raise ValueError("仅支持CSV、XLS、XLSX格式的输入文件") # 批量添加节点 for _, row in nodes_df.iterrows(): G.add_node(row['node_id'], **row.to_dict()) # 批量添加边 for _, row in edges_df.iterrows(): G.add_edge(row['from_node'], row['to_node'], **row.to_dict()) return G, nodes_df def draw_flowchart(G, nodes_df): # 节点样式映射,可根据需求自定义修改 style_map = { 'start': {'color': '#2ECC71', 'shape': 'o', 'size': 3000}, 'process': {'color': '#3498DB', 'shape': 's', 'size': 4000}, 'decision': {'color': '#F1C40F', 'shape': 'D', 'size': 5000}, 'end': {'color': '#E74C3C', 'shape': 'o', 'size': 3000} } # 生成层级布局 if 'level' in nodes_df.columns: # 优先使用手动指定的层级 level_dict = nodes_df.set_index('node_id')['level'].to_dict() else: # 无手动层级时自动通过拓扑排序生成分层 topo_order = list(nx.topological_sort(G)) level_dict = {node: idx for idx, node in enumerate(topo_order)} pos = nx.multipartite_layout(G, subset_key=lambda n: level_dict[n], align='horizontal') # 按类型绘制节点 for node_type, style in style_map.items(): target_nodes = [n for n, attr in G.nodes(data=True) if attr.get('node_type') == node_type] nx.draw_networkx_nodes(G, pos, nodelist=target_nodes, node_color=style['color'], node_shape=style['shape'], node_size=style['size']) # 绘制节点文本 nx.draw_networkx_labels(G, pos, labels={n: attr['node_label'] for n, attr in G.nodes(data=True)}, font_size=10) # 绘制带箭头的边 nx.draw_networkx_edges(G, pos, arrowstyle='->', arrowsize=20) # 绘制边的标签 edge_labels = {(u, v): attr.get('edge_label', '') for u, v, attr in G.edges(data=True)} nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels, font_size=9) plt.axis('off') plt.tight_layout() plt.show() # 调用示例 if __name__ == '__main__': # 替换为你的文件路径即可 G, nodes_df = build_flowchart('流程图数据.xlsx') draw_flowchart(G, nodes_df)
3. 特殊规则适配说明
- 如果流程图存在循环分支,拓扑排序会失效,手动给节点表加
level列指定每个节点的层级即可正常布局 - 需自定义节点/边的样式(比如虚线、自定义颜色形状)时,直接在对应数据表加属性列,修改绘图逻辑读取属性配置即可
- 如需导出为可交互的HTML流程图,可将绘图部分替换为
pyvis库实现,逻辑完全通用
内容的提问来源于stack exchange,提问作者Sahil Merali
相关产品推荐
相关产品推荐

