Search code examples
pythonplotseaborn

seaborn histogram to have different color bins


A simple histogram by seaborn. I want to highlight the top 3 bins with a different color. Here shows a matplotlib way, but not a seaborn way.

Is there any ways to show different colored bins in seaborn?

Thank you.

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

data = np.random.normal(loc = 6, size=100)
ax = sns.distplot(data, bins = 20)
plt.xlim(0, 10)
plt.show()

enter image description here


Solution

  • If there are no other plots on the same ax, you could loop through all its patches, find the 3 highest and color them:

    import numpy as np
    import seaborn as sns
    import matplotlib.pyplot as plt
    
    data = np.random.normal(loc = 6, size=500)
    ax = sns.distplot(data, bins = 20)
    
    heights = [p.get_height() for p in ax.patches]
    third_highest = sorted(heights)[-3]
    for p in ax.patches:
        if  p.get_height() >= third_highest:
            p.set_color('crimson')
    
    plt.xlim(0, 10)
    plt.show()
    

    example plot