Search code examples
pythonpython-3.xmatplotlibseabornpairplot

Seaborn pairplot with log scale only for specific columns


I have a dataframe and I'm using seaborn pairplot to plot one target column vs the rest of the columns.

Code is below,

import seaborn as sns
import matplotlib.pyplot as plt

tgt_var = 'AB'
var_lst = ['A','GH','DL','GT','MS']

pp = sns.pairplot(data=df,
          y_vars=[tgt_var],
          x_vars=var_lst)

pp.fig.set_figheight(6)
pp.fig.set_figwidth(20)

The var_lst is not a static list, I just provided an example. What I need is to plot tgt_var on Y axis and each var_lst on x axis.

I'm able to do this with above code, but I also want to use log scale on X axis only if the var_lst item is 'GH' or 'MS', for the rest normal scale. Is there any way to achieve this?


Solution

  • Iterate pp.axes.flat and set xscale="log" if the xlabel matches "GH" or "MS":

    log_columns = ["GH", "MS"]
    
    for ax in pp.axes.flat:
        if ax.get_xlabel() in log_columns:
            ax.set(xscale="log")
    

    Full example with the iris dataset where the petal columns are xscale="log":

    import seaborn as sns
    
    df = sns.load_dataset("iris")
    pp = sns.pairplot(df)
    
    log_columns = ["petal_length", "petal_width"]
    
    for ax in pp.axes.flat:
        if ax.get_xlabel() in log_columns:
            ax.set(xscale="log")
    

    iris pairplot where petal columns have log x-scale