pythonpandasmatplotlibseabornhistplot

How to change the color of individual bars in histplot


I was looking on internet but i didn't get any solution.

I have this graph and I want to change the color of the first bar, if I use the parameter 'color' it changes all the bars.

seaborn graph

Is it possible to do this?


Solution

  • You could access the list of generated rectangles via ax.patches, and then recolor the first one:

    import matplotlib.pyplot as plt
    import seaborn as sns
    import pandas as pd
    import numpy as np
    
    df = pd.DataFrame({'Sales': 100000 * (np.random.rand(80) ** 1.5) + 18000})
    ax = sns.histplot(x='Sales', data=df, bins=4, color='skyblue', alpha=1)
    ax.patches[0].set_facecolor('salmon')
    plt.show()
    

    sns.histplot recolor bins

    To get a separation exactly at 40.000, you could create two histograms on the same subplot. With binrange= exact limits can be set:

    import matplotlib.pyplot as plt
    import seaborn as sns
    import pandas as pd
    import numpy as np
    
    df = pd.DataFrame({'Sales': 100000 * (np.random.rand(80) ** 1.5) + 18000})
    # either choose a fixed limit, or set it exactly at one fourth
    limit = 40000
    # limit = df['Sales'].min() + 0.25 * (df['Sales'].max() - df['Sales'].min())
    ax = sns.histplot(x='Sales', data=df[df['Sales'] <= limit],
                      bins=1, binrange=(df['Sales'].min(), limit), color='salmon')
    sns.histplot(x='Sales', data=df[df['Sales'] > limit],
                 bins=3, binrange=(limit, df['Sales'].max()), color='skyblue', ax=ax)
    plt.show()
    

    sns.histplot with binrange