Search code examples
pythonbar-chartseabornvisualizationjitter

Connecting jittered data points with lines - seaborn python


Is there a way to extract the x-axis values of the jittered points in the middle plot as generated by the code below?

See the issue here

# import libraries
import seaborn as sns
import matplotlib.pyplot as plt

# Create plot
ax2 = fig.add_subplot(132)
sns.stripplot(x="variable", y="value", data=pupil_long_df, dodge=True, jitter=True, alpha=.40, zorder=1, size=8, linewidth = 1)
sns.pointplot(x='variable', y='value', ci=95,data=pupil_long_df, join=False, scale=1, zorder=100, color='black', capsize = 0.05, palette = 'Paired') 

# Add lines between the points
lines3 = plt.plot([df.iloc[:,0], df.iloc[:,1]], color = 'grey', linewidth = 0.5, linestyle = '--')



Solution

  • I think it would be terribly impractical to extract the x-values of the stripplot... My standard advice is that if you want to do something more than the standard plots offered by seaborn, then it's usually easier to just recreate them by hand. See the code below:

    N=20
    # dummy dataset
    data = np.random.normal(size=(N,))
    df = pd.DataFrame({'condition 1': data,
                       'condition 2': data+1,
                       'condition 3': data,
                       'condition 4': data-1})
    
    jitter = 0.05
    df_x_jitter = pd.DataFrame(np.random.normal(loc=0, scale=jitter, size=df.values.shape), columns=df.columns)
    df_x_jitter += np.arange(len(df.columns))
    
    fig, ax = plt.subplots()
    for col in df:
        ax.plot(df_x_jitter[col], df[col], 'o', alpha=.40, zorder=1, ms=8, mew=1)
    ax.set_xticks(range(len(df.columns)))
    ax.set_xticklabels(df.columns)
    ax.set_xlim(-0.5,len(df.columns)-0.5)
    
    for idx in df.index:
        ax.plot(df_x_jitter.loc[idx,['condition 1','condition 2']], df.loc[idx,['condition 1','condition 2']], color = 'grey', linewidth = 0.5, linestyle = '--', zorder=-1)
        ax.plot(df_x_jitter.loc[idx,['condition 3','condition 4']], df.loc[idx,['condition 3','condition 4']], color = 'grey', linewidth = 0.5, linestyle = '--', zorder=-1)
    

    enter image description here