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
- Manual X-Offset: We created
x_posto shiftNpoints left by 0.1 andYpoints right by 0.1 relative to the centralTreatmentposition. This replaces the problematic dodge behavior with explicit, controlled positioning. - Grouped Lines: Using
group='Individual'for both dots and lines ensures each line connects only the paired points belonging to the same individual. - Clean X-Axis: The
scale(x=...)setting ensures the x-axis displays only theTreatmentlabel ('A') at the center of the shifted points.
内容的提问来源于stack exchange,提问作者gbarl
相关产品推荐
相关产品推荐

