You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Seaborn FacetGrid绘制两个同列名DataFrame的分面对比直方图

实现思路

直接合并两个数据集并新增分组标识列,借助Seaborn原生的hue参数即可自动在同一分面叠加两组的直方图,无需手动遍历分面添加图层,容错率更高。

完整实现代码

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

# 1. 合并数据集并添加分组标识
df1_Sample['group'] = '药物处理组'
df1_Control['group'] = '对照组'
df_combined = pd.concat([df1_Sample, df1_Control], ignore_index=True)

# 2. 提取所有特征列(排除Compound和新增的group标识列)
feature_cols = [col for col in df_combined.columns if col not in ['Compound', 'group']]

# 3. 遍历每个特征生成分面对比图
for feature in feature_cols:
    # 初始化分面网格,col_wrap参数可根据需要调整每行展示的分面数量
    g = sns.FacetGrid(df_combined, col='Compound', col_wrap=3, height=4, hue='group')
    # 绘制叠加直方图,alpha设置透明度避免遮挡,可自行调整bins数量
    g.map(sns.histplot, feature, alpha=0.6, bins=20, element='bars')
    # 添加图例与标题调整
    g.add_legend()
    g.set_titles(col_template='分组:{col_name}')
    g.set_axis_labels(x_var=feature, y_var='样本频数')
    # 优化布局
    plt.tight_layout()
    # 按需保存图片,文件名关联特征名
    # plt.savefig(f'{feature}_组间分布对比.png', dpi=200, bbox_inches='tight')
    plt.show()

可选优化

  • 如果需要叠加核密度估计曲线,可在sns.histplot参数中添加kde=True
  • 如果觉得柱状叠加辨识度低,可将element='bars'改为element='step'绘制空心轮廓直方图

内容的提问来源于stack exchange,提问作者Ardalan1

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 20:06:05