How to use a different colormap for different rows of a heatmap

Viewed 392

I am trying to change 1 row in my heatmap to a different color

here is the dataset:

m = np.array([[ 0.7,  1.4,  0.2,  1.5,  1.7,  1.2,  1.5,  2.5],
              [ 1.1,  2.5,  0.4,  1.7,  2. ,  2.4,  2. ,  3.2],
              [ 0.9,  4.4,  0.7,  2.3,  1.6,  2.3,  2.6,  3.3],
              [ 0.8,  2.1,  0.2,  1.8,  2.3,  1.9,  2. ,  2.9],
              [ 0.9,  1.3,  0.8,  2.2,  1.8,  2.2,  1.7,  2.8],
              [ 0.7,  0.9,  0.4,  1.8,  1.4,  2.1,  1.7,  2.9],
              [ 1.2,  0.9,  0.4,  2.1,  1.3,  1.2,  1.9,  2.4],
              [ 6.3, 13.5,  3.1, 13.4, 12.1, 13.3, 13.4, 20. ]])
data = pd.DataFrame(data = m)

Right now I am using seaborn heatmap, I can only create something like this:

cmap = sns.diverging_palette(240, 10, as_cmap = True)
sns.heatmap(data, annot = True, cmap = "Reds")
plt.show

enter image description here

I hope to change the color scheme of the last row, here is what I want to achieve (I did this in Excel):

enter image description here

Is it possible I achieve this in Python with seaborn heatmap? Thank you!

1 Answers

You can split in two, mask the unwanted parts, and plot separately:

# Reds
data1 = data.copy()
data1.loc[7] = float('nan')
ax = sns.heatmap(data1, annot=True, cmap="Reds")

# Greens
data2 = data.copy()
data2.loc[:6] = float('nan')
sns.heatmap(data2, annot=True, cmap="Greens")

output:

two colors heatmap

NB. you need to adapt the loc[…] parameter to your actual index names

Related