Search code examples
pythonseabornfacet-gridxticks

How to set ticks in Seaborn FacetGrid?


I have a code like this, and I want to add ticks on the X-axis so I could see better what the value over 150 corresponds to, for example. the range for my X-values is from 178 to 17639.

bins = np.linspace(df.days_with_cr_line.min(), df.days_with_cr_line.max(), 32)

g = sns.FacetGrid(df, col="loan_status", hue="loan_status", palette=['#8856a7', '#f03b20'], col_wrap=2)
g.map(plt.hist, 'days_with_cr_line', bins=bins, ec="k")

enter image description here

I have tried

g.set_xticks(np.arange(0,18000,500), minor=True)
AttributeError: 'FacetGrid' object has no attribute 'set_xticks'

and

for axes in g.axes.flat:
    _ = axes.set_xticks(axes.get_xticks(range(0,18000)))

this removes the tick labels without adding any ticks.


Solution

  • If you use set to set the number of ticks on the x-axis, and then set the tick labels for them, you will get the intended result. The data is created appropriately.

    import pandas as pd
    import numpy as np
    import seaborn as sns
    import matplotlib.pyplot as plt
    
    np.random.seed(20210831)
    df = pd.DataFrame({'days_with_cr_line':np.random.randint(10,1000,size=1000),
                      'loan_status':np.random.choice(['Fully paid','Not fully paid'], size=1000)})
    bins = np.linspace(df.days_with_cr_line.min(), df.days_with_cr_line.max(), 32)
    
    g = sns.FacetGrid(df, col="loan_status", hue="loan_status", palette=['#8856a7', '#f03b20'], col_wrap=2)
    g.map(plt.hist, 'days_with_cr_line', bins=bins, ec="k")
    g.set(xticks=np.arange(0,1050,50))
    g.set_xticklabels(np.arange(0,1050,50), rotation=90)
    

    enter image description here