Use Listed colors or Linear Segmented Colormap from Matplotlib, eg. like in this question (Discrete legend in seaborn heatmap plot):

myColors = ((0.8, 0.0, 0.0, 1.0), (0.0, 0.8, 0.0, 1.0), (0.0, 0.0, 0.8, 1.0))

cmap = LinearSegmentedColormap.from_list('Custom', myColors, len(myColors))

You can specify your colours using RGB or also hex format. However, seaborn provides many predefined palettes, see https://seaborn.pydata.org/tutorial/color_palettes.html.

Answer from My Work on Stack Overflow
๐ŸŒ
Seaborn
seaborn.pydata.org โ€บ generated โ€บ seaborn.heatmap.html
seaborn.heatmap โ€” seaborn 0.13.2 documentation - PyData |
seaborn.heatmap(data, *, vmin=None, vmax=None, cmap=None, center=None, robust=False, annot=None, fmt='.2g', annot_kws=None, linewidths=0, linecolor='white', cbar=True, cbar_kws=None, cbar_ax=None, square=False, xticklabels='auto', yticklabels='auto', mask=None, ax=None, **kwargs)#
๐ŸŒ
Python Graph Gallery
python-graph-gallery.com โ€บ the python graph gallery โ€บ heatmap โ€บ control color in seaborn heatmaps
Control color in seaborn heatmaps
2 weeks ago - # library import seaborn as sns ... code? Let AI write it for you ยท You can customize the colors in your heatmap with the cmap parameter of the heatmap() function in seaborn....
๐ŸŒ
Apryor6
apryor6.github.io โ€บ visualizations โ€บ seaborn โ€บ heatmap โ€บ heatmap
seaborn.heatmap
plt.rcParams['font.size'] = 20 bg_color = (0.88,0.85,0.95) plt.rcParams['figure.facecolor'] = bg_color plt.rcParams['axes.facecolor'] = bg_color fig, ax = plt.subplots(1) p = sns.heatmap(df, cmap='coolwarm', annot=True, fmt=".1f", annot_kws={'size':16}, ax=ax) plt.xlabel('Month') plt.ylabel('Year') ax.set_ylim((0,15)) plt.text(5,12.3, "Heat Map", fontsize = 95, color='Black', fontstyle='italic')
๐ŸŒ
Seaborn
seaborn.pydata.org โ€บ archive โ€บ 0.11 โ€บ generated โ€บ seaborn.heatmap.html
seaborn.heatmap โ€” seaborn 0.11.2 documentation
seaborn.heatmap(data, *, vmin=None, vmax=None, cmap=None, center=None, robust=False, annot=None, fmt='.2g', annot_kws=None, linewidths=0, linecolor='white', cbar=True, cbar_kws=None, cbar_ax=None, square=False, xticklabels='auto', yticklabels='auto', mask=None, ax=None, **kwargs)ยถ ยท
๐ŸŒ
DataCamp
datacamp.com โ€บ tutorial โ€บ seaborn-heatmaps
Seaborn Heatmaps: A Guide to Data Visualization | DataCamp
December 13, 2024 - To use seaborn.heatmap(), you typically need to pass in a matrix of data. Then, you can adjust the parameters to customize your heatmaps depending on your requirements. data: The dataset to visualize, which must be in a matrix form. cmap: Specifies the colormap for the heatmap.
๐ŸŒ
datagy
datagy.io โ€บ home โ€บ data visualization โ€บ python seaborn โ€บ seaborn heatmap: a complete guide
Seaborn heatmap: A Complete Guide โ€ข datagy
April 18, 2023 - # Changing the Size of a Seaborn Heatmap import seaborn as sns import matplotlib.pyplot as plt import pandas as pd df = read_data() fig, ax = plt.subplots(figsize=(14, 6)) sns.heatmap(df, cmap='coolwarm', square=True) plt.show()
๐ŸŒ
Statology
statology.org โ€บ home โ€บ how to make heatmaps with seaborn (with examples)
How to Make Heatmaps with Seaborn (With Examples)
January 18, 2021 - #set heatmap size import matplotlib.pyplot as plt plt.figure(figsize = (12,8)) #create heatmap sns.heatmap(data) We can use the cmap argument to change the colors used in the heatmap.
๐ŸŒ
Stack Abuse
stackabuse.com โ€บ ultimate-guide-to-heatmaps-in-seaborn-with-python
Ultimate Guide to Heatmaps in Seaborn with Python
September 27, 2023 - It is easy to change the colors that Seaborn uses to draw the heatmap by specifying the optional cmap (colormap) parameter.
Find elsewhere
๐ŸŒ
Seaborn
seaborn.pydata.org โ€บ archive โ€บ 0.12 โ€บ generated โ€บ seaborn.heatmap.html
seaborn.heatmap โ€” seaborn 0.12.2 documentation
seaborn.heatmap(data, *, vmin=None, vmax=None, cmap=None, center=None, robust=False, annot=None, fmt='.2g', annot_kws=None, linewidths=0, linecolor='white', cbar=True, cbar_kws=None, cbar_ax=None, square=False, xticklabels='auto', yticklabels='auto', mask=None, ax=None, **kwargs)#
๐ŸŒ
Medium
medium.com โ€บ @1zeyneper โ€บ data-visualization-with-seaborn-heatmaps-58abfadd79d5
Data Visualization with Seaborn: Heatmaps | by Zeynep | Medium
March 10, 2024 - Then, you can adjust the parameters ... .data: The dataset to visualize, which must be in a matrix form. .cmap: Specifies the colormap for the heatmap....
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ seaborn-heatmap-a-comprehensive-guide
Seaborn Heatmap - A comprehensive guide - GeeksforGeeks
March 29, 2025 - Values lower than 30 are represented ... Example 2: The cmap parameter allows us to modify the color scheme of the heatmap, improving its visual appeal and making it easier to distinguish between different values....
Top answer
1 of 4
3

Consider the following:

import matplotlib as mpl
import seaborn as sns
import numpy as np

A = np.random.randint(0,100, size=(20,20))
mask_array = np.zeros((20, 20), dtype=bool)
mask_array[:, :5] = True
cmap = mpl.colormaps["viridis"]

newcolors = cmap(np.linspace(0, 1, 100))
newcolors[:10] = np.array([1,1,1,1])
newcolors[90:] = np.array([0,0,0,1])
newcolors[20] = mpl.colors.to_rgb('tab:orange') + (1,)

newcmap = mpl.colors.ListedColormap(newcolors)

g = sns.heatmap(A, cmap=newcmap, mask=mask_array)
# Set color of masked region
g.set_facecolor('lightgrey')

Sample result:

The following (appended to the above script) will make it so that the colorbar has a visible outline.

cbar_ax = g.figure.axes[-1]

for spine in cbar_ax.spines.values():
    spine.set(visible=True)

Sample result with outline:


In order to mask the colors of the heatmap, but not show an updated colorbar, set cbar=False, and then attach a custom colorbar, as shown in Standalone colorbar.

g = sns.heatmap(A, cmap=newcmap, mask=mask_array, cbar=False)

# add a new axes of the desired shape
cb = g.figure.add_axes([0.93, 0.11, 0.025, 0.77])

# attach a new colorbar to the axes
mpl.colorbar.ColorbarBase(cb, cmap='viridis', norm=mpl.colors.Normalize(10, 90),  # vmax and vmin
                          label=None, ticks=range(10, 91, 10))

2 of 4
3
  • The difficulty arises from the requirement to use more than a single mask.
    • mask_array, and a mask for A == 20 if the array is only int, or 20 <= A < 21 if the array is float.
  • matplotlib.colors.Colormap offers only 3 methods for setting colors.
    1. set_under
    2. set_over
    3. set_bad - Set the color for masked values, which is already used for mask_array.
    • with_extremes - Does the three combined.
      • cmap = mpl.colormaps['viridis'].with_extremes(bad='orange', under='w', over='k')
    • Using these methods doesn't effect the look of the colorbar.

Imports and Sample Data

import numpy as np
import seaborn as sns
import matplotlib as mpl

# set for repeatable sample
np.random.seed(2023)

# random 20 x 20 array
# A = np.random.randint(0, 100, size=(20, 20))  # random integers
A = np.random.random(size=(20, 20)) * 100  # random floats

1. Don't show the sliced columns

  • This is the easiest option, because it frees up mask
# remove the unneeded columns
A = A[:, 5:]

# create the value mask
mask = np.logical_and(A >= 20, A < 21)

# create the colormap with extremes
cmap = mpl.colormaps["viridis"].with_extremes(bad='orange', under='w', over='k')

# plot
g = sns.heatmap(A, vmin=10, vmax=90, cmap=cmap, mask=mask)

# reset the xticklabels to show the correct column labels
_ = g.set_xticks(ticks=g.get_xticks(), labels=range(5, 20))

2. Show all the columns

  • This is the more cumbersome option because, like the answer provided by Ben, this requires manually adding a color to cmap, and adding a custom colorbar.
    • Using mask, or any np.nan values in the array, are colored by set_bad.
  • This reuses the colorbar creation method I previously added to Ben's answer, which came from Standalone colorbar.
  • As demonstrated in Creating Colormaps in Matplotlib, a new color can be added into a slice of colors from a resampled colormap.
    • This does not get the correct value if vmin and vmax are used, because those options change the range of the colorbar.
# create the column mask
mask = np.zeros((20, 20), dtype=bool)
mask[:, :5] = True  # A[:, :5] = np.nan has the same effect

# slice the colors into the range of values in the array
colors = mpl.colormaps["viridis"].resampled(100).colors

# map a specific value range to a color; use a range for floats, and / or set a hight number to resampled
colors[19:21] = mpl.colors.to_rgba('tab:orange')

# create the new colormap with extremes
cmap = mpl.colors.ListedColormap(colors).with_extremes(bad='lightgray', under='w', over='k')

# draw the heatmap
g = sns.heatmap(A, cmap=cmap, mask=mask, cbar=False)

# add a new axes of the desired shape
cb_ax = g.figure.add_axes([0.93, 0.11, 0.025, 0.77])

# attach a new colorbar to the axes without an outline
cb = mpl.colorbar.ColorbarBase(cb_ax, cmap='viridis', norm=mpl.colors.Normalize(10, 90),  # vmax and vmin
                               label=None, ticks=range(10, 91, 10)).outline.set_visible(False)

3. Let the columns and bad values share the color

# create the value mask
mask = np.logical_and(A >= 20, A < 21)

# add the unwanted column to the mask as np.nan
mask[:, :5] = np.nan

# create the colormap with extremes
cmap = mpl.colormaps["viridis"].with_extremes(bad='orchid', under='w', over='k')

# plot
g = sns.heatmap(A, vmin=10, vmax=90, cmap=cmap, mask=mask)

Top answer
1 of 2
4

As an alternative to the accepted answer you could also set vmin to slightly above 0 and define the color for out-of-range values with set_under:

import copy
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np

cmap = copy.copy(plt.get_cmap("Reds"))
cmap.set_under('#009933')
sns.heatmap(np.random.randint(0,10,(10,10)), cmap=cmap, lw=0.005, annot=True, vmin=1e-5)

The under-color is not shown by default in the colorbar. To alter the colorbar, use for example sns.heatmap(..., cbar_kws={'extend':'min', 'extendrect':True}). The explanation of these parameters can be found in the colorbar docs.

2 of 2
2

You can use a LinearSegmentedColormap from matplotlib.colors. You first have to find the largest value, in this case 10, then use that to create a colors variable that starts with green, then goes to the standard 'Reds' colorset. Also, set the colorbar to False when making the heatmap with seaborn, and separately make one with matplotlib.

This code was adapted from here:

import matplotlib.pyplot as plt
import matplotlib.colors as cl
import seaborn as sns
import pandas as pd
import numpy as np
import random

data = []
for i in range(10):
    data.append([random.randrange(0, 11, 1) for _ in range(10)])
df = pd.DataFrame(data)

fig, ax = plt.subplots(figsize = (12, 10)) 
cmap_reds = plt.get_cmap('Reds')
num_colors = 11
colors = ['#009933'] + [cmap_reds(i / num_colors) for i in range(1, num_colors)]
cmap = cl.LinearSegmentedColormap.from_list('', colors, num_colors)
ax = sns.heatmap(df, cmap=cmap, vmin=0, vmax=num_colors, square=True, cbar=False, annot = True)
cbar = plt.colorbar(ax.collections[0], ticks=range(num_colors + 1))
cbar.set_ticks(np.linspace(0, num_colors, 2*num_colors+1)[1::2])
cbar.ax.set_yticklabels(range(num_colors))
plt.show()

Here is the output:

๐ŸŒ
Python Basics
pythonbasics.org โ€บ home โ€บ matplotlib & seaborn โ€บ seaborn heatmap
seaborn heatmap - pythonbasics.org
import pandas as pd import numpy as np import seaborn as sns import matplotlib.pyplot as plt df = pd.DataFrame(np.random.randn(50).reshape(10,5)) corr = df.corr() ax1 = sns.heatmap(corr, cbar=0, linewidths=2,vmax=1, vmin=0, square=True, cmap='Blues') plt.show()
๐ŸŒ
Bestin-it
bestin-it.com โ€บ home โ€บ seaborn heatmaps: a complete guide for data visualization
Seaborn Heatmap Parameters: annot, cmap, vmin, vmax Explained
August 3, 2026 - Some of the most common and useful parameters are: data: The data to plot, must be a two-dimensional array or a DataFrame. cmap: The color map to use for the heatmap, can be a string or a colormap object.
๐ŸŒ
Seaborn
seaborn.pydata.org โ€บ tutorial โ€บ color_palettes.html
Choosing color palettes โ€” seaborn 0.13.2 documentation
Because they are intended to represent ... the corresponding data values. Seaborn includes four perceptually uniform sequential colormaps: "rocket", "mako", "flare", and "crest". The first two have a very wide luminance range and are well suited for applications such as heatmaps, ...
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ colormaps-in-seaborn-heatmaps
ColorMaps in Seaborn HeatMaps - GeeksforGeeks
November 25, 2020 - Since "Greens" is an inbuilt colormap in seaborn, can also directly pass "Greens" to the cmap argument: ... import seaborn as sns import numpy as np np.random.seed(0) data = np.random.rand(12, 12) ax = sns.heatmap(data, cmap="Greens")
๐ŸŒ
EDUCBA
educba.com โ€บ home โ€บ data science โ€บ data science tutorials โ€บ seaborn tutorial โ€บ seaborn heatmap
Seaborn heatmap | Learn the Various Examples of Seaborn heatmap
May 31, 2023 - In the above example we have plotted the heatmap with the feature known as cmap where we can use different color palettes from the seaborn library.
Address: Unit no. 202, Jay Antariksh Bldg, Makwana Road, Marol, Andheri (East),, 400059, Mumbai