How to assign colors to values in a seaborn heatmap

Question:

I have a data frame with 15 rows and 15 columns and the values are whole numbers in the range(0-5).

I use this data frame to create multiple heatmaps by filtering the data.

In the heatmap, I want to assign particular colors to every value so that even if the number of unique values in the data frame varies for every heatmap, the colors remain consistent for every assigned value.

Using the fixed color code, I want to use a single legend key for all the heat maps.

How can I assign colors with a dictionary?

cmap_dict = {0:'#FFFFFF',1:'#ff2a00', 2:'#ff5500', 3:'#ff8000', 4:'#ffaa00', 5:'#ffd500'}

heat_map = sns.heatmap(df,square=False,yticklabels=True,xticklabels=False,cmap=cmap1,vmin=0,vmax=5,cbar=False, annot=False)
Asked By: Yash

||

Answers:

If you set vmin and vmax the mapping from numbers to colors will always be the same, also when some values are missing from the data.

Some ideas:

  • Use a ListedColormap with the given list of 6 colors
  • Set vmin=-0.5, vmax=5.5 to have the values 0,1,2,3,4,5 nicely at the center of each color.
  • As seaborn by default makes the colorbar border invisible, and one of the colors is white, the colorbar border could be turned visible.
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
import seaborn as sns
import pandas as pd
import numpy as np

cmap_dict = {0: '#FFFFFF', 1: '#ff2a00', 2: '#ff5500', 3: '#ff8000', 4: '#ffaa00', 5: '#ffd500'}
cmap = ListedColormap([cmap_dict[i] for i in range(6)])
df = pd.DataFrame(np.random.randint(0, 6, size=(15, 15)), index=[*'abcdefghijklmno'])

ax = sns.heatmap(data=df, cmap=cmap, vmin=-0.5, vmax=5.5, yticklabels=True, xticklabels=False)

for spine in ax.collections[0].colorbar.ax.spines.values():
    spine.set_visible(True) # show the border of the colorbar
plt.tight_layout()
plt.show()

sns.heatmap with fixed mapping between numbers and colors

Answered By: JohanC