Search code examples
pythonseaborn

How to set the range in which a density is shown in seaborn


I have the following plots

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

# read some dataframe and

sns.histplot(data=df['error'],bins=20, binrange=(0,2),kde=True)

enter image description here

so you can see I have limited the range for the histogram but not for the curve. Also the curve looks suspiciously low (and wrong)

then

sns.histplot(data=df['c0_right_error'],bins=40, binrange=(-2,2),kde=True)

gives me

enter image description here

I also tried the density plot (which I don't know if it is correct or not)

sns.histplot(data=df['c0_right_error'],bins=40, binrange=(-2,2),kde=True, stat='density')

enter image description here

How can I limit the range in these plots?


Solution

  • You need to use ax.set_xlim using the matplotlib library. Using a dummy dataset see code below:

    import pandas as pd
    import numpy as np
    import seaborn as sns
    import matplotlib.pyplot as plt
    
    df = pd.DataFrame({'a':np.random.normal(size=1000)})
    fig, ax = plt.subplots()
    sns.histplot(data=df['a'],bins=40, binrange=(-2,2),kde=True, stat='density', ax=ax)
    ax.set_xlim(-1, 1)
    plt.show()
    

    enter image description here