0

I am using seaborn to plot the heritability of some brain regions. I want to highlight the labels on the x-axis based on the brain regions. So for example, let's say that I have regions that are White matter and regions that are grey matter. I want to highlight the brain regions of the grey matter in red and the white matter regions in blue. How can I do that?

Here is the code that I use:

b = sns.barplot(x="names", y="h2" ,data=df, ax = ax1)
ax1.set_xticklabels(labels= df['names'].values.ravel(),rotation=90,fontsize=5)
ax1.errorbar(x=list(range (0,165)),y=df['h2'], yerr=df['std'], fmt='none', c= 'b')
plt.tight_layout()
plt.title('heritability  of regions ')
plt.show()

What should I add to do what I want? Thanks

wwla
  • 41
  • 1
  • 9

1 Answers1

2

You can add a new column to the dataframe and use that as the hue parameter. To change the color of the ticklabels, you can loop through them and use set_color depending on the grey/white column.

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

df = pd.DataFrame({'names': list('abcdefghij'),
                   'h2': np.random.randint(10, 100, 10),
                   'grey/white': np.random.choice(['grey', 'white'], 10)})
ax1 = sns.barplot(x='names', y='h2', hue='grey/white', dodge=False, data=df)
ax1.set_xticklabels(labels=df['names'], rotation=90, fontsize=15)
# ax1.errorbar(x=list(range(0, 165)), y=df['h2'], yerr=df['std'], fmt='none', c='b')
for (greywhite, ticklbl) in zip(df['grey/white'], ax1.xaxis.get_ticklabels()):
    ticklbl.set_color('red' if greywhite == 'grey' else 'blue')
plt.title('heritability  of regions ')
plt.tight_layout()
plt.show()

example plot

JohanC
  • 71,591
  • 8
  • 33
  • 66