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

如何使用seaborn violinplot绘制数值总和而非计数的小提琴图

基于权重的Seaborn小提琴图绘制方案

你可以直接使用seaborn.violinplot内置的weights参数实现需求,无需对原始数据集进行全量展开,仅需要预计算每个数值的出现频次作为权重即可,仅这一步处理后数据量最多只有10000条(匹配你提到的1-10000的取值范围),完全不会有性能压力。

单变量场景实现代码

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

# 你的原始数据集
df = pd.DataFrame({'quantity':[1,1,1,4]})

# 统计每个数值的出现频次作为权重
weight_df = df['quantity'].value_counts().reset_index()
weight_df.columns = ['quantity', 'weight']

# 绘制加权小提琴图,效果和你手动展开后的结果完全一致
sns.violinplot(data=weight_df, x='quantity', weights='weight')
plt.show()

配合catplot的多分组场景实现代码

如果需要按类别分组绘制小提琴图,仅需要在统计权重时增加分组维度即可:

# 示例带分组的原始数据集
df = pd.DataFrame({
    'group': ['实验组']*4 + ['对照组']*5,
    'quantity': [1,1,1,4, 2,2,3,3,3]
})

# 按分组+数值统计对应权重
weight_df = df.groupby(['group', 'quantity']).size().reset_index(name='weight')

# 用catplot绘制分组加权小提琴图
sns.catplot(
    data=weight_df,
    x='group',
    y='quantity',
    kind='violin',
    weights='weight'
)
plt.show()

注意事项

weights参数是Seaborn 0.13.0及以上版本新增的特性,如果运行时报错请先升级Seaborn:
pip install --upgrade seaborn

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 04:18:03