如何基于字典使用Matplotlib绘制多张子图
解决方案
先确定子图布局:固定每行显示4张图,行数根据字典条目数向上取整(比如条目数为5时,行数设为2)。通过plt.subplots创建统一画布与子图数组,遍历字典条目和对应子图完成绘制,最后统一调整布局并展示。
修改后的完整代码如下:
import matplotlib.pyplot as plt import math # 假设win_size、get_windows函数已提前定义 total_plots = len(sequences) cols = 4 rows = math.ceil(total_plots / cols) # 创建画布和子图数组,flatten转为一维方便遍历 fig, axes = plt.subplots(rows, cols, figsize=(16, 4*rows)) axes = axes.flatten() for idx, (seq_name, seq_data) in enumerate(sequences.items()): current_ax = axes[idx] # 计算x轴与GC比例数据 x = range(0, len(seq_data) - win_size() + 1) gc_ratios = [] for window in get_windows(seq_data): gc_count = window.count("g") + window.count("c") gc_ratios.append(gc_count / len(window)) # 在当前子图绘制曲线 current_ax.plot(x, gc_ratios) current_ax.set_title(seq_name) current_ax.set_xlabel("nucleotide position") current_ax.set_ylabel("gc proportion") # 隐藏多余的空白子图(当条目数不是4的整数倍时) for idx in range(total_plots, rows*cols): axes[idx].axis('off') # 自动调整子图间距,避免元素重叠 plt.tight_layout() plt.show()
核心调整说明:
- 用
math.ceil(total_plots / cols)计算行数,确保所有字典条目都能分配到子图 axes.flatten()将二维子图数组转为一维,无需区分行列,遍历更简洁- 仅在最后调用一次
plt.show(),所有子图会一次性展示在同一块画布上 - 隐藏多余空白子图,优化视觉效果;
tight_layout()自动调整间距,避免标题、标签互相遮挡
内容的提问来源于stack exchange,提问作者maevemoon
相关产品推荐
相关产品推荐

