使用Python,networkx绘制有向层级结构图
- 1. 效果图
- 2. 源码
- 2.1 tree.txt
- 2.2 pyNetworkx.py
- 参考
上一篇介绍了:1. 使用Python,networkx对卡勒德胡赛尼三部曲之《群山回唱》人物关系图谱绘制
当前博客介绍: 2. 使用Python,networkx绘制有向层级结构图
下一篇将介绍: 3. 使用Python,maplotlib绘制树型有向层级结构图
1. 效果图
可以分别绘制圆型布局、随机布局、Spring布局、贝壳布局、星型布局图
圆型布局图如下,并且对部分点设置不同颜色不同大小:
随机布局图如下,并且对部分点设置不同颜色不同大小:
Spring布局效果图如下,并且对部分点设置不同颜色不同大小:
贝壳布局图如下,并且对部分点设置不同颜色不同大小:
星型布局图,并且对部分点设置不同颜色不同大小:
2. 源码
2.1 tree.txt
A,B,a-b
A,C,hello
A,D,a-d
B,E,good
B,F,b-f
B,G,b-g
C,H,good
C,I,c-i
H,J,h-j
J,K,bad
J,Z,j-z
E,L,bad
2.2 pyNetworkx.py
# python pyNetworkx.py
# 对层级结构图谱进行绘制import sysimport matplotlib.pyplot as plt
import networkx as nxprint(sys.getdefaultencoding())
print(plt.rcParams['backend'])plt.rcParams['backend'] = 'TkAgg'# 支持中文
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = Falsenodes = []
edegs = []
edegLabels = dict()
with open("res/tree.txt", 'r', encoding='utf-8', errors='ignore') as f:data = f.readlines()for i, line in enumerate(data):print(i, line.replace("\n", ""))nodes.append(line.split(",")[0])nodes.append(line.split(",")[1])edegs.append((line.split(",")[0], line.split(",")[1]))edegLabels[(line.split(",")[0], line.split(",")[1])] = line.split(",")[2]nodes = list(set(nodes))print('nodes: ', nodes)print(edegs)original_graph = nx.DiGraph()node_sizes = [200 if i % 6 == 0 else 50 for i, n in enumerate(nodes)]
node_colors = ["green" if i % 5 == 0 else "blue" if i % 6 == 0 else "red" for i, n in enumerate(nodes)]print('nodeSize: ', node_sizes)original_graph.add_nodes_from(nodes)
original_graph.add_edges_from(edegs)base_options = dict(with_labels=True, edgecolors="blue")# 圆型布局、随机布局、Spring布局、贝壳布局、星型布局
posList = [nx.circular_layout(original_graph), nx.random_layout(original_graph), nx.spring_layout(original_graph),nx.shell_layout(original_graph), nx.spectral_layout(original_graph)]for j, pos1 in enumerate(posList):print(pos1)fig, ax = plt.subplots(figsize=(8, 8))plt.title(str(j) + " Original (%s edges)" % original_graph.number_of_edges())nx.draw_networkx(original_graph, pos=pos1, node_color=node_colors, **base_options)# 绘制标签nx.draw_networkx_edge_labels(original_graph, pos=pos1, edge_labels=edegLabels)# 缩放图表以保证标签可读# ax.margins(0.1, 0.05)# plt.tight_layout()plt.show()
参考
- 使用Python,networkx对卡勒德胡赛尼三部曲之——《群山回唱》人物关系图谱绘制
- https://networkx.org/documentation/latest/reference/drawing.html
- https://blog.csdn.net/qq_45956730/article/details/127352658