Python中如何将排列函数的输出绘制成排列图?
你要的这种排列对比可视化可以通过Python的matplotlib库实现,完整可运行代码如下,保留了你原本的排列生成逻辑:
from itertools import permutations import matplotlib.pyplot as plt # 你原有的排列生成函数 def permutate(string): letters = [x for x in string] perms = list(permutations(letters, len(letters))) p_set = set([''.join(i) for i in perms]) return sorted(p_set) # 生成排列列表 perm_list = permutate('abab') str_length = len(perm_list[0]) # 自定义不同字符对应的展示颜色 color_map = {'a': '#1f77b4', 'b': '#ff7f0e'} plt.figure(figsize=(7, 4), dpi=100) # 遍历每个排列绘制对应位置的字符标记 for y, perm in enumerate(perm_list): for x, char in enumerate(perm): plt.scatter(x, y, s=220, c=color_map[char], zorder=3) # 如需在圆点内显示字符,去掉下一行注释即可 # plt.text(x, y, char, ha='center', va='center', c='white', fontweight='bold') # 可选:添加同字符位置的连接虚线,不需要可以删掉下面这段 for char in color_map: char_pos = [[] for _ in range(str_length)] for y, perm in enumerate(perm_list): for x, c in enumerate(perm): if c == char: char_pos[x].append(y) for x, y_list in enumerate(char_pos): if len(y_list) >= 2: plt.plot([x]*len(y_list), y_list, c=color_map[char], linestyle='--', alpha=0.6, zorder=2) # 调整坐标轴显示样式 plt.yticks(range(len(perm_list)), perm_list, fontsize=12) plt.xticks(range(str_length), [f'第{i+1}位' for i in range(str_length)], fontsize=12) plt.gca().invert_yaxis() # 翻转Y轴,让第一个排列显示在最上方 plt.grid(alpha=0.3, zorder=1) plt.tight_layout() plt.show()
运行上述代码即可生成你预期的排列图效果,你也可以根据需求调整参数自定义样式:
- 修改
color_map字典的值可以更换不同字符的显示颜色 - 修改
scatter方法的s参数可以调整圆点的大小 - 修改
figsize参数可以调整画布的长宽比例
内容的提问来源于stack exchange,提问作者MartynaMajch
相关产品推荐
相关产品推荐

