0

I'd like to customize my seaborn heatmap plot, by adding an extra bar on the y-axis that would illustrate the label of my indices.

Here is a toy example to illustrate my need:

test = pd.DataFrame.from_dict({"A": [np.random.randint(10) for _ in range(10)],
                               "B": [np.random.randint(10) for _ in range(10)],
                               })

sns.heatmap(test)

heatmap

Let's say I have labels for each one of the Pandas indices like:

labels = ["class1", "class1", "class1",  "class1", "class1", "class2", "class2", "class3", "class3", "class3"]

I'd like to add to the heatmap a bar on the y-axis with one color per label.

Thank you very much for your help !

PS: I saw this cool answer for seaborn.clustermap How to express classes on the axis of a heatmap in Seaborn

But I don't think I directly applies to seaborn.heatmap

pklein
  • 3
  • 4
  • Maybe it would help if you'd add a mockup of the desired plot. Does it include a legend? Are there explicit labels for each of the y ticks? You linked to a post with a clustermap without clusters, so basically it is just a heatmap. Why isn't it applicable to your situation? – JohanC Mar 20 '23 at 23:31

1 Answers1

0

You are right @JohanC I apologize.

I thought I could not use clustermap because I did not want to do any clustering but just show labels on the side of the heatmap.

test = pd.DataFrame.from_dict({"A": [np.random.randint(10) for _ in range(10)],
                               "B": [np.random.randint(10) for _ in range(10)],
                               })
                               
row_colors = pd.Series(["r", "r", "r", "r", "r", "b", "b", "g", "g", "g"])
labels_to_color = {0: "r", 1: "b", 2: "g"}

g = sns.clustermap(data=test, row_cluster=False, col_cluster=False, row_colors=row_colors)

for label in labels_to_color.keys():
    g.ax_col_dendrogram.bar(0, 0, color=labels_to_color[label],
                            label=label, linewidth=0)
g.ax_col_dendrogram.legend(loc="center", ncol=6)

It shows the labels as a barplot on the left side as expected.

clustermap_with_labels

pklein
  • 3
  • 4