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

如何使用seaborn/pandas/matplotlib绘制多特征对比箱线图?

箱线图实现方案

原有代码问题

  • 未按seaborn API规范传递参数,重复传入departure_delay字段,且未关联satisfaction维度
  • 原始数据为宽表结构,出发延误、到达延误为独立列,无法直接在同一图表中对比展示

实现步骤

1. 数据预处理

首先将宽表转换为长表格式,统一两个延误字段的存储结构:

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

# 数据重构,提取需要的维度转为长表
melted_df = satis_df.melt(
    id_vars=['customer_type', 'satisfaction'],
    value_vars=['departure_delay', 'arrival_delay'],
    var_name='delay_type',
    value_name='delay_minutes'
)

2. 绘图代码

版本1:单画布嵌套分组展示

适合直接在同一画布对比所有维度:

plt.figure(figsize=(15, 8))
sns.boxplot(
    data=melted_df,
    x='customer_type',
    y='delay_minutes',
    hue='satisfaction',
    palette='Set2'
)
plt.title('Figure 7: Boxplot', fontsize=15)
plt.xlabel('客户类型', fontsize=12)
plt.ylabel('延误时长(分钟)', fontsize=12)
plt.legend(title='满意度', bbox_to_anchor=(1.01, 1), loc='upper left')
plt.tight_layout()
plt.show()

版本2:分面展示(更清晰区分延误类型)

如果需要同时明确展示出发/到达延误两个维度,可使用分面绘图:

sns.catplot(
    data=melted_df,
    x='delay_type',
    y='delay_minutes',
    hue='satisfaction',
    col='customer_type',
    kind='box',
    height=6,
    aspect=0.9,
    palette='coolwarm'
)
plt.suptitle('Figure 7: Boxplot', y=1.03, fontsize=15)
plt.tight_layout()
plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 21:39:03