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

如何分离重叠的小提琴图?附现有代码及问题图示

解决小提琴图重叠问题

不需要使用双轴(twinx()),正确的做法是将数据转换为长格式,利用Seaborn的hue参数让同一soa分组下的两个小提琴图自动并排展示,避免重叠。

具体步骤:

  • 用pandas.melt()将宽格式数据转换为长格式,把perf_congr和perf_incongr合并为数值列,新增列标记数据类别;
  • 调用一次sns.violinplot(),通过hue参数区分两类数据,Seaborn会自动将同一x分组的小提琴图分开排列。

修改后的代码:

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

# 转换数据格式为长格式
eyehead_perf_long = pd.melt(
    eyehead_perf,
    id_vars=['soa'],  # 保留的分组列
    value_vars=['perf_congr', 'perf_incongr'],  # 需要合并的数值列
    var_name='perf_type',  # 新的类别列名称
    value_name='perf_value'  # 新的数值列名称
)

fig, ax = plt.subplots()
hue_order = np.unique(eyehead_perf['soa'])

# 绘制小提琴图,hue区分两类数据,自动并排
sns.violinplot(
    data=eyehead_perf_long,
    x='soa',
    y='perf_value',
    hue='perf_type',
    inner='point',
    gap=0.2,  # 调整同一分组下两个小提琴的间距
    ax=ax,
    common_norm=True
)

plt.legend(title='Performance Type')
plt.show()

原代码重叠原因:

原代码使用twinx()创建了共享x轴的双y轴,两个小提琴图的x轴位置完全重合,因此会重叠在一起。而通过长格式+hue参数的方式,Seaborn会自动调整同一x分组下不同hue类别的小提琴位置,实现并排展示。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 15:15:00