Home > front end >  How to invert the axis of a seaborn figure-level plot (FacetGrid)
How to invert the axis of a seaborn figure-level plot (FacetGrid)

Time:09-17

I would like to invert the y-axis in each plot of a Facetgrid.

Below you find a reduced example of the code:

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

df_test = pd.DataFrame({'a':['yes', 'no']*5, 'b':np.arange(10), 'c':np.arange(10)*2})
plt.figure()
g = sns.FacetGrid(data=df_test, row='a')
g.map_dataframe(sns.scatterplot, y='c', x='b')
plt.show()

enter image description here

As far as I know, this is normally done with ax.invert_yaxis() when using matplotlib, so I tried to access it through g.axes but had no luck.

I am aware that I can manually set a ylim=(max_val, min_val), however, this results in unsightly tick spacing.

CodePudding user response:

  • Extract and set each axes, by iterating through g.axes
  • Tested in python 3.8.11, matplotlib 3.4.3, seaborn 0.11.2
g = sns.FacetGrid(data=df_test, row='a')
g.map_dataframe(sns.scatterplot, y='c', x='b')

for ax in g.axes[0]:
    ax.invert_yaxis()
  • However, using enter image description here

    • Use .ravel() to flatten n x n arrays or axes, where both n > 1
    df_test = pd.DataFrame({'a':['yes', 'no', 'maybe']*4, 'b':np.arange(12), 'c':np.arange(12)*2, 'd': np.arange(12)*3})
    
    g = sns.relplot(data=df_test, col='a', col_wrap=2, x='b', y='c', kind='scatter', height=3)
    for ax in g.axes.ravel():
        ax.invert_yaxis()
    

    enter image description here

  • Related