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

Seaborn面向对象接口绘制配对数据:解决分组额外偏移问题

Solution for Paired Plot with Connected Lines in Seaborn Objects

Problem Analysis

Your original code uses so.Dodge(by=['fill']) alongside group="Individual", which causes unintended horizontal shifts for lines—this happens because dodge is applied per individual group instead of globally for the Treated category. Without grouping, lines connect all points instead of pairing each individual's N and Y measurements.

Fixed Code

We’ll manually adjust the x-position of points based on the Treated value to separate N and Y points, then connect each individual’s paired points with lines:

import numpy as np
import pandas as pd
import seaborn.objects as so

np.random.seed(0)
df = pd.DataFrame({
    'Treated': ['N']*10 + ['Y']*10,
    'Treatment': ['A']*20,
    'value': np.random.random(20),
    'Individual': [str(i) for i in list(range(10)) + list(range(10))],
    'Genotype': (['WT']*5 + ['M1']*5)*2
})

# Add numerical x-position column with offsets for Treated groups
df['x_pos'] = df['Treatment'].replace({'A': 0}) + df['Treated'].replace({'N': -0.1, 'Y': 0.1})

p = (
    so.Plot(df, x='x_pos', y='value', color='Genotype', fill='Treated')
    # Plot dots for each measurement
    .add(so.Dot(), group='Individual')
    # Connect paired points for each individual (no legend for lines)
    .add(so.Line(), group='Individual', legend=None)
    # Set x-axis to show only 'A' at the center
    .scale(x=so.Continuous(breaks=[0], labels=['A']))
    # Maintain fill color order for Treated
    .scale(fill=so.Nominal(['N', 'Y'], order=["N", "Y"]))
)
p.show()

Key Changes

  1. Manual X-Offset: We created x_pos to shift N points left by 0.1 and Y points right by 0.1 relative to the central Treatment position. This replaces the problematic dodge behavior with explicit, controlled positioning.
  2. Grouped Lines: Using group='Individual' for both dots and lines ensures each line connects only the paired points belonging to the same individual.
  3. Clean X-Axis: The scale(x=...) setting ensures the x-axis displays only the Treatment label ('A') at the center of the shifted points.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 08:04:55