pythonmatplotlibseabornx-axiscatplot

Remove some xtick labels from a seaborn plot


In the screenshot below, all my x-labels are overlapping each other.

g = sns.factorplot(x='Age', y='PassengerId', hue='Survived', col='Sex', kind='strip', data=train);

I know that I can remove all the labels by calling g.set(xticks=[]), but is there a way to just show some of the Age labels, like 0, 20, 40, 60, 80?

enter image description here


Solution

  • I am not sure why there aren't sensible default ticks and values like there are on the y-axis.

    The FormatStrFormatter instance is necessary to supply set_major_formatter. The %d is from the format specification mini-language.

    import seaborn as sns
    import matplotlib.pyplot as plt
    import matplotlib.ticker as ticker
    
    titanic = sns.load_dataset('titanic')
    sns.factorplot(x='age',y='fare',hue='survived',col='sex',data=titanic,kind='strip')
    ax = plt.gca()
    ax.xaxis.set_major_formatter(ticker.FormatStrFormatter('%d'))
    ax.xaxis.set_major_locator(ticker.MultipleLocator(base=20))
    plt.show()
    

    enter image description here


    This also works with catplot, which replaced factorplot

    titanic = sns.load_dataset('titanic')
    sns.catplot(x='age', y='fare', hue='survived', col='sex', data=titanic, kind='strip')
    ax = plt.gca()
    ax.xaxis.set_major_formatter(ticker.FormatStrFormatter('%d'))
    ax.xaxis.set_major_locator(ticker.MultipleLocator(base=20))
    plt.show()
    

    enter image description here