Home > database >  Seaborn: How to change the color of individual bars in histogram?
Seaborn: How to change the color of individual bars in histogram?

Time:02-21

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? Thank u so much!

CodePudding user response:

Use:

import seaborn as sns
s = [1,1,2,2,1,3,4]
s = pd.DataFrame({'val': s, 'col':['1' if x==1 else '0' for x in s]})
sns.histplot(data=s, x="val", hue="col")

The output:

enter image description here

CodePudding user response:

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

CodePudding user response:

Well, the exact way will depend on which mapping software you are using. Your best bet is to break your data into two sets, one for the first bar and one for the rest. You should be able to output each of the sets in its own colour.

  • Related