0

I have a barchart in Seaborn, and want to colour specific bars based upon the value of a categorical variable, y.

data = {'symbol': ['apple', 'banana', 'pear', 'aubergine'],
        'value': [7, 5,6,3]}

df_c = pd.DataFrame(data)

fig, ax = plt.subplots(figsize=(5,10)) 
g = sns.barplot(data=df_c.head(50), y='symbol', x= 'value',color='black', ci=None)
ax.patches[35].set_facecolor('red')

Example Seaborn plot

I have a (bad) solution that lets me colour a bar by its position in the list (e.g. I count down and apply ax.patches with a slice, but what I'd ideally like to be able to do is pass a list containing the categorical values of y, e.g. ['apple', 'banana'...]

Is this an option with a Seaborn barplot?

molcode
  • 25
  • 4

2 Answers2

1

You can use palette:

clrs = ['grey' if (x in ['banana', 'pear'] ) else 'red' for x in df_c['symbol'] ]
g = sns.barplot(data=df_c.head(4), y='symbol', x= 'value', palette=clrs, ci=None)

Output:

enter image description here

Another example:

import matplotlib.pyplot as plt

import seaborn as sns
import pandas as pd

data = {'symbol': ['apple', 'banana', 'pear', 'aubergine'],
        'value': [7, 5,6,3]}

df_c = pd.DataFrame(data)

fig, ax = plt.subplots(figsize=(5,10)) 
clrs = ['grey' if (x < 4) else 'red' for x in df_c['value'] ]

g = sns.barplot(data=df_c.head(4), y='symbol', x= 'value', palette=clrs, ci=None)

Output:

enter image description here

Shahab Rahnama
  • 982
  • 1
  • 7
  • 14
1

I recommend using matplotlib, easyier than seaborn, check the code below

data = {'symbol': ['apple', 'banana', 'pear', 'aubergine'],
        'value': [7, 5,6,3]}
df = pd.DataFrame(data)
color_map = ['#f5f5f1' for _ in range(len(df))]
for idx, value in enumerate(df.value):
    if value > 5:
        color_map[idx] = '#b20710' # highlight color
        
fig, ax = plt.subplots() 
ax.barh(df.symbol, df.value, height=0.6, 
       edgecolor='darkgray',
       linewidth=0.6,color=color_map)

enter image description here

jianan1104
  • 101
  • 1
  • 5