基于DataFrame双列数据按sample_id分类的小提琴图绘制需求
按Sample ID拆分的小提琴图绘制方案
需求说明
现有包含1000行数据的DataFrame,列结构如下:
sample_id | chi_2_n_est | chi_2_n_theo --------------------------------------- 1 | 1.01 | 1.001 1 | 1.03 | 1.012 ... 2 | 1.11 | 1.04 3 | 1.21 | 1.03 ...
需要为chi_2_n_est和chi_2_n_theo列绘制小提琴图,按sample_id拆分,对比每个样本ID下两类数据的分布,蓝色代表chi_2_n_est,橙色代表chi_2_n_theo。
实现方案
使用pandas处理数据格式,seaborn绘制小提琴图,步骤如下:
- 导入依赖库
import pandas as pd import seaborn as sns import matplotlib.pyplot as plt
- 转换数据格式
将宽表转为长格式,适配seaborn的分组绘图逻辑:
# 假设你的DataFrame变量名为df melted_df = df.melt(id_vars='sample_id', value_vars=['chi_2_n_est', 'chi_2_n_theo'], var_name='data_type', value_name='value')
- 绘制小提琴图
设置分组规则、配色并完成绘图:
# 设置绘图风格 sns.set_style("whitegrid") # 创建画布 plt.figure(figsize=(10, 6)) # 绘制拆分式小提琴图 sns.violinplot(data=melted_df, x='sample_id', y='value', hue='data_type', split=True, # 同一Sample ID下的两个分布共用小提琴左右半区 palette={'chi_2_n_est': '#1f77b4', 'chi_2_n_theo': '#ff7f0e'}, # 指定蓝橙配色 inner='quartile') # 内部显示四分位数线 # 设置图表标签与标题 plt.title('chi_2_n_est vs chi_2_n_theo Distribution by Sample ID', fontsize=14) plt.xlabel('Sample ID', fontsize=12) plt.ylabel('Value', fontsize=12) # 调整图例位置 plt.legend(title='Data Type', loc='upper right') # 展示图形 plt.show()
关键参数说明
split=True:让同一Sample ID下的两类数据分布在同一个小提琴图的左右两侧,更便于直观对比palette:严格匹配需求的蓝橙配色,对应两类数据列inner='quartile':在小提琴内部标注四分位数,辅助观察数据的离散程度
内容的提问来源于stack exchange,提问作者twistfire
相关产品推荐
相关产品推荐

