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

如何用Pandas与Seaborn绘制自定义起止与中线的分类箱线图

自定义箱线图绘制需求及解决方法

原始数据准备

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

data = [['Math', 3, 5, 15],
        ['English', 3, 10, 20],
        ['Computers', 5, 12, 30],
        ['Science', 8, 15, 32],
        ['Art', 17, 25, 48],
        ['Sports', 22, 45, 60]]
    
df = pd.DataFrame(data, columns=['Class', 'First Rank','Second Rank', 'Third Rank'])

需求说明

需要为每个Class绘制箱线图,要求:

  • 箱体起始值对应First Rank列
  • 箱体中线对应Second Rank列
  • 箱体结束值对应Third Rank列

尝试的代码及问题

以下代码生成的箱线图不符合需求:

df2 = pd.melt(df, ['Class'])
g = sns.catplot(x="value", y='Class', hue='Class', data=df2, errorbar=None, native_scale=True, kind="box", orient="h", height=5, aspect=2)
g.set(xticks=(range(0, 80, 5)))

问题在于:该代码基于数据统计生成箱线图,会展示置信区间相关元素,无法严格按照指定的三列值定义箱体的起止和中线。

期望的图样式为:
图中数字仅为示意,无需显示
目标箱线图样式

正确实现代码

直接使用matplotlib的boxplot手动定义箱体参数,即可生成符合要求的图:

import matplotlib.pyplot as plt
import pandas as pd

data = [['Math', 3, 5, 15],
        ['English', 3, 10, 20],
        ['Computers', 5, 12, 30],
        ['Science', 8, 15, 32],
        ['Art', 17, 25, 48],
        ['Sports', 22, 45, 60]]
    
df = pd.DataFrame(data, columns=['Class', 'First Rank','Second Rank', 'Third Rank'])

# 构造每个类别的箱体数据:[下限, 下限, 中位数, 上限, 上限]
# 确保boxplot生成的箱体严格匹配指定的起止和中线
box_data = []
for _, row in df.iterrows():
    box_data.append([row['First Rank'], row['First Rank'], row['Second Rank'], row['Third Rank'], row['Third Rank']])

# 绘制水平箱线图
plt.figure(figsize=(10,5))
box = plt.boxplot(box_data, vert=False, labels=df['Class'], patch_artist=True)
# 可选:设置箱体颜色
for patch in box['boxes']:
    patch.set_facecolor('#8888ff')
# 设置x轴刻度
plt.xticks(range(0, 80, 5))
plt.xlabel('Rank')
plt.ylabel('Class')
plt.title('Class Rank Boxplot')
plt.tight_layout()
plt.show()

说明

seaborn的箱线图基于数据分布统计生成,无法直接指定箱体固定起止值。而matplotlib的boxplot可以通过构造特定格式的输入数据,强制箱体的下限、中位数、上限完全匹配指定列值,同时通过重复起止值实现无箱须的效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 01:57:14