Search code examples
pythonmatplotlibseaborn

Seaborn plot: Adjust row and column labels


I have the following plot:

Plot

However, the labels for rows and columns are just concatenated and overlap. Can I adjust those labels? Ideally, a line break should be used instead of a pipe.

Here is example code to create a similar plot with the same problem:

import numpy as np
import pandas as pd
import seaborn as sns


df1 = pd.DataFrame(
    np.zeros((6,6)),
    columns=['Epoch', 'Correlation', 'PreprocessingStyle', 'Model', 'Dataset', 'Type'],
)
df1['Model'] = 'a' * 26
df1['PreprocessingStyle'] = 'b' * 26

df2 = pd.DataFrame(
    np.zeros((6,6)),
    columns=['Epoch', 'Correlation', 'PreprocessingStyle', 'Model', 'Dataset', 'Type'],
)
df2['Model'] = 'c' * 26
df2['PreprocessingStyle'] = 'd' * 26


df = pd.concat([df1, df2])

g = sns.relplot(
    df,
    x='Epoch',
    y='Correlation',
    col='PreprocessingStyle',
    row='Model',
    hue='Dataset',
    style='Type',
    kind='line',
    markers=True,
    dashes=False,
)

Solution

  • Assuming you want a newline between the columns and rows descriptions, you could customize the title with set_titles.

    For example, using the tips dataset:

    import seaborn as sns
    
    tips = sns.load_dataset('tips').rename(columns={'time': 'quite long column name'})
    
    (sns.relplot(data=tips, x="total_bill", y="tip", hue="day",
                 col="quite long column name", row="sex",
                 height=3, aspect=1, facet_kws={'gridspec_kws': {'hspace': 0.3}})
        .set_titles('{row_var}: {row_name}\n{col_var}: {col_name}')
    )
    

    enter image description here