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

基于Pandas多层索引DataFrame绘制多箱线图的实现需求

解决方案:按Method生成Metric箱线图

没问题,我来帮你实现这个需求!下面是结合Pandas和Matplotlib/Seaborn的具体实现步骤,能帮你为每个Method生成单独的、包含对应Metric箱线图的图表。

步骤1:导入依赖库

先导入需要的工具库:

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns  # 可选,用来美化图表样式

步骤2:构造示例多层索引DataFrame

先还原你给出的示例数据(实际使用时替换成你的真实数据即可):

# 创建多层索引行
index = pd.MultiIndex.from_tuples(
    [('HASH', 'L2_TCM'), ('HASH', 'TOT_CYC'),
     ('RECV', 'L2_TCM'), ('RECV', 'TOT_CYC'),
     ('SYNTH', 'L2_TCM'), ('SYNTH', 'TOT_CYC')],
    names=['method', 'metric']
)
# 创建DataFrame,列代表不同样本
df = pd.DataFrame({
    0: [287, 6211, 331, 10881, 869, 29117],
    1: [296, 6100, 323, 7524, 856, 29560]
}, index=index)

步骤3:数据重塑为长格式

原始数据是宽格式(列对应样本),我们需要转成长格式,方便按method和metric分组绘图:

# 将样本列转为行索引,再重置索引得到长格式数据
long_df = df.stack().reset_index()
# 重命名列名,让含义更清晰
long_df.columns = ['method', 'metric', 'sample_id', 'value']

转换后的数据结构示例:

methodmetricsample_idvalue
HASHL2_TCM0287
HASHL2_TCM1296
HASHTOT_CYC06211
............

步骤4:按Method批量绘制箱线图

遍历每个method,为其单独生成一张包含所有metric箱线图的图表:

# 设置图表风格(可选,用seaborn美化)
sns.set_style("whitegrid")

# 获取所有唯一的method
unique_methods = long_df['method'].unique()

# 遍历每个method绘图
for method in unique_methods:
    # 筛选当前method的数据
    method_data = long_df[long_df['method'] == method]
    
    # 创建画布
    plt.figure(figsize=(8, 6))
    
    # 绘制箱线图:x轴为metric,y轴为对应样本值
    sns.boxplot(data=method_data, x='metric', y='value', palette='Set2')
    
    # 设置图表标题和标签
    plt.title(f'Metric Distribution for Method: {method}', fontsize=14)
    plt.xlabel('Metric', fontsize=12)
    plt.ylabel('Value', fontsize=12)
    
    # 自动调整布局,避免标签被截断
    plt.tight_layout()
    
    # 显示图表(如果需要保存,可添加plt.savefig(f'{method}_boxplot.png'))
    plt.show()

关键说明

  • 数据重塑是核心步骤:把宽格式转成长格式后,能更便捷地用seaborn的boxplot按metric分组展示数据分布。
  • 即使你的样本数量很多,箱线图也能自动呈现中位数、四分位数、异常值等分布特征,完全匹配你的需求。
  • 如果不需要seaborn的美化,直接用Matplotlib原生的boxplot也可以,只是需要手动整理每个metric的样本数据,代码会稍显繁琐。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:04:49