Search code examples
pythonpandasmatplotlibseabornlmplot

How to plot seaborn lmplots in multiple subplots


I was trying to plot multiple lmplots in the same figure. But I am getting too many unwanted subplots.

I found another SO link How to plot 2 seaborn lmplots side-by-side? but that also did not help me.

In this example I want 1 row 2 columns.

MWE

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

# data
df = sns.load_dataset('titanic')

# plot
m,n = 1,2
figsize=(12,8)
cols1 = ['age','fare']
cols2 = ['fare','age']
target = 'survived'
fontsize = 12

fig, ax = plt.subplots(m,n,figsize=figsize)
for i, (col1,col2) in enumerate(zip(cols1,cols2)):
    plt.subplot(m,n,i+1)

    sns.lmplot(x=col1,y=col2,data=df,
           hue=target, palette='Set1',
           scatter_kws={'alpha':0.3})

    plt.xlabel(col1,fontsize=fontsize)
    plt.ylabel(col2,fontsize=fontsize)

    plt.tick_params(axis='both', which='major', labelsize=fontsize)
    plt.tight_layout()

for i in range(m*n-len(cols1)):
    ax.flat[-(i+1)].set_visible(False)

Solution

  • My attempt so far:

    df = pd.DataFrame({'x0':[10,20,30,40],
                       'y0': [100,200,300,400],
                       'x1':[0.1,0.2,0.3,0.1],
                       'y1':[0.01,0.02,0.03,0.01],
                       'target': [0,1,1,1]
                       })
    
    df1 = df.append(df)
    df1 = df1.reset_index(drop=True)
    df1['x0'].iloc[len(df):] = df['x1'].to_numpy()
    df1['y0'].iloc[len(df):] = df['y1'].to_numpy()
    df1['col'] = ['c0']* len(df) + ['c1'] * len(df)
    df1 = df1.drop(['x1','y1'],axis=1)
    df1 = df1.rename(columns={'x0':'x','y0':'y'})
    
    sns.lmplot(x='x',y='y',hue='target',data=df1,col='col')
    

    Output: enter image description here