如何使Matplotlib imshow与dna_features_viewer的X轴物理刻度对齐?
解决Matplotlib imshow与DNA Features Viewer绘图X轴对齐问题
问题根源
imshow默认启用aspect='equal',强制图像宽高比一致,导致子图宽度被限制,无法和下方DNA Features Viewer生成的子图X轴物理长度匹配;同时两者的X轴索引范围也存在细微差异。
修复步骤
- 给
imshow添加aspect='auto'参数,让图像自适应子图宽度 - 调整
ax0的X轴范围,与DNA Features Viewer的Genbank索引(1到850)对齐
修改后的完整代码
from dna_features_viewer import GraphicFeature, GraphicRecord import matplotlib from matplotlib import rcParams import matplotlib.pyplot as plt import numpy as np import pandas as pd rcParams["figure.figsize"] = 15, 12 fig, (ax0, ax1) = plt.subplots(2, 1, height_ratios=[5, 1], sharex=True) # ax0 - 修改部分:添加aspect='auto',设置xlim匹配genbank索引 data_heatmap = np.random.rand(850, 850) # 关键:添加aspect='auto'取消等宽高比限制 heatmap = ax0.imshow(data_heatmap, cmap="bone", aspect='auto') fig.colorbar(heatmap, ax=ax0) ax0.set_xlabel("Scored Residue") ax0.set_ylabel("Aligned Residue") ax0.set_ylim(len(data_heatmap) + 1, 1) # 调整X轴范围,对应1-850的genbank索引(imshow默认是0-849,加0.5偏移匹配) ax0.set_xlim(0.5, 850.5) # ax1 domains = pd.DataFrame({"domain": ["dom1", "dom2", "dom3"], "start": [9, 516, 714], "end": [459, 689, 850], "color": ["#0000b6", "#02eded", "#ab0000"]}) features = [] for _, row in domains.iterrows(): features.append(GraphicFeature(start=row["start"], end=row["end"], strand=+1, color=row["color"], label=row["domain"])) record = GraphicRecord(sequence_length=row["end"] + 1, features=features, plots_indexing="genbank") record.plot(ax=ax1) plt.tight_layout() plt.show()
原理说明
aspect='auto'让imshow图像不再强制等宽高,而是填充整个子图宽度,和下方子图的X轴物理长度保持一致- 设置
xlim(0.5, 850.5)是因为imshow的每个像素中心对应整数坐标,这样调整后,X轴的1-850刻度会和DNA Features Viewer的序列位置精准对齐
内容的提问来源于stack exchange,提问作者Mesmer
相关产品推荐
相关产品推荐

