Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change the color for ytick labels in seaborn.clustermap

Tags:

python

seaborn

Is it possible to change the colors of the ytick labels in seaborn.clustermap?

So for the seaborn Iris example, it is possible to set row colors based on species and plot a clustermap:

import seaborn as sns
iris = sns.load_dataset("iris")
species = iris.pop("species")
lut = dict(zip(species.unique(), "rbg"))
row_colors = species.map(lut)
g = sns.clustermap(iris)

And it is possible to get a 1-1 correspondence between the plotted row and row label:

g.ax_heatmap.yaxis.get_majorticklabels()

Is there anyway to use this to recolor the ytick labels based on row_colors?

like image 254
gōshafoc Avatar asked Nov 14 '17 18:11

gōshafoc


1 Answers

I found this question while trying to do the same, after looking further this answer by @tom set me on track to customize the tick labels.

You need to specify the color for each individual tick by mapping the text in the tick label back to the color dictionary.

To get access to each tick go for g.ax_heatmap.axes.get_yticklabels(), then extract the text of the tick using get_text().

In the particular example of the Iris dataset the tick labels text are indices of the pandas series species, to gather the species text that allows you to recover the color from the lut dictionary you need to convert the index back to an int and use .loc to extract the info needed.

iris = sns.load_dataset("iris")
species = iris.pop("species")
lut = dict(zip(species.unique(), "rbg"))
row_colors = species.map(lut)
g = sns.clustermap(iris, row_colors=row_colors)

for tick_label in g.ax_heatmap.axes.get_yticklabels():
    tick_text = tick_label.get_text()
    species_name = species.loc[int(tick_text)]
    tick_label.set_color(lut[species_name])

Iris dataset clustermap with colored ticks in the y axis

You will notice some "mismatches" in the colors of the dendrogram and the y axis tick labels(for example 97 and 114), this is due to the size of the figure. Increasing the size using figsize lets you uncover the hidden ticks. enter image description here

like image 61
ppflrs Avatar answered Oct 02 '22 15:10

ppflrs