Mark K
Mark K

Reputation: 9338

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

Upvotes: 0

Views: 3082

Answers (2)

Arnaud Borrens
Arnaud Borrens

Reputation: 11

Stumbled across this question today too and JohanC's answer worked very well!

One little addition I would add is that if you like your bars to have borders you can swap the p.set_color with p.set_facecolor, that way if your original plot has bars with borders it will keep the borders intact.

Upvotes: 1

JohanC
JohanC

Reputation: 80279

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

Upvotes: 3

Related Questions