如何在H/E/C构象占比饼图外添加氨基酸分布环形图层?
问题描述
现有如下CSV格式的氨基酸构象计数数据:
,H,E,C A,8393.0,2872.0,5649.0 R,4360.0,2188.0,3892.0 N,2029.0,1137.0,4714.0 D,3234.0,1436.0,6761.0 C,754.0,743.0,1185.0 Q,3529.0,1278.0,2844.0 E,6649.0,2053.0,5248.0 G,2338.0,2200.0,10054.0 H,1389.0,1006.0,2112.0 I,4348.0,4210.0,2734.0 L,8642.0,4386.0,5590.0 K,4805.0,2194.0,4895.0 M,1884.0,913.0,1459.0 F,2767.0,2377.0,2601.0 P,1397.0,987.0,6678.0 S,3136.0,2226.0,6094.0 T,2986.0,2884.0,4950.0 W,987.0,787.0,930.0 Y,2218.0,2145.0,2205.0 V,4689.0,5950.0,3699.0
已通过以下代码绘制出展示H、E、C三种构象占比的饼图:
ss_dist_df=pd.read_csv("counts", index_col=0) plt.pie(ss_dist_df.sum(), autopct='%1.1f%%', startangle=90)
现需要在该饼图外侧添加环形图层,展示每种构象(H、E、C)对应的20种氨基酸的分布情况。
实现方案
要实现这种双层嵌套饼图(内层为构象总占比,外层为各构象下的氨基酸分布),可以通过Matplotlib的pie函数配合半径、楔形属性设置来完成,具体步骤如下:
1. 数据预处理
先整理内层构象总计数和外层各构象下的氨基酸计数:
import pandas as pd import matplotlib.pyplot as plt # 读取数据 ss_dist_df = pd.read_csv("counts", index_col=0) # 内层:H/E/C三种构象的总计数 inner_counts = ss_dist_df.sum() # 外层:按构象分组,展开所有氨基酸的计数 outer_counts = [] for col in ss_dist_df.columns: outer_counts.extend(ss_dist_df[col].tolist()) # 外层标签:格式为「构象-氨基酸」,方便区分归属 outer_labels = [f"{col}-{aa}" for col in ss_dist_df.columns for aa in ss_dist_df.index]
2. 绘制双层饼图
通过设置不同半径和楔形宽度,区分内外层结构:
# 设置画布大小,避免标签拥挤 plt.figure(figsize=(10,10)) # 绘制内层饼图:构象占比 wedges_inner, texts_inner, autotexts_inner = plt.pie( inner_counts, autopct='%1.1f%%', startangle=90, radius=0.7, # 内层半径更小 wedgeprops=dict(width=0.3, edgecolor='white') # 预留外层环形空间 ) # 绘制外层环形图:各构象下的氨基酸分布 wedges_outer, texts_outer = plt.pie( outer_counts, labels=outer_labels, startangle=90, radius=1.0, # 外层半径更大 wedgeprops=dict(width=0.3, edgecolor='white') ) # 调整布局,优化显示 plt.tight_layout() plt.show()
3. 可选优化细节
- 解决标签重叠:如果外层标签过多,可将图例移至图外侧:
plt.legend(wedges_outer, outer_labels, loc="upper right", bbox_to_anchor=(1.3, 0.9)) - 视觉区分构象:为同一构象下的氨基酸设置统一色系,增强辨识度:
# 定义三种构象的专属颜色 conf_colors = ['#ff9999','#66b3ff','#99ff99'] outer_colors = [] for idx, col in enumerate(ss_dist_df.columns): outer_colors.extend([conf_colors[idx]]*len(ss_dist_df.index)) # 绘制外层时指定颜色参数 wedges_outer, texts_outer = plt.pie( outer_counts, labels=outer_labels, startangle=90, radius=1.0, colors=outer_colors, wedgeprops=dict(width=0.3, edgecolor='white') )
内容的提问来源于stack exchange,提问作者Caterina
相关产品推荐
相关产品推荐

