🌐
Seaborn
seaborn.pydata.org › generated › seaborn.heatmap.html
seaborn.heatmap — seaborn 0.13.2 documentation - PyData |
sns.heatmap(glue, cmap="crest") Or pass a colormap object: sns.heatmap(glue, cmap=sns.cubehelix_palette(as_cmap=True)) Set the colormap norm (data values corresponding to minimum and maximum points): sns.heatmap(glue, vmin=50, vmax=100) Use methods on the matplotlib.axes.Axes object to tweak the plot: ax = sns.heatmap(glue, annot=True) ax.set(xlabel="", ylabel="") ax.xaxis.tick_top()
🌐
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
sns.heatmap(df) <matplotlib.axes._subplots.AxesSubplot at 0x10c53b7b8> cmap adjusts the colormap used. I like diverging colormaps for heatmaps because they provide good contrast. sns.heatmap(df, cmap='coolwarm') <matplotlib.axes._subplots.AxesSubplot at 0x10c65d710> center can be used to indicate at which numeric value to use the center of the colormap.
🌐
GeeksforGeeks
geeksforgeeks.org › python › 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")
🌐
DataCamp
datacamp.com › tutorial › seaborn-heatmaps
Seaborn Heatmaps: A Guide to Data Visualization | DataCamp
December 13, 2024 - # Create an annotated heatmap plt.figure(figsize = (10,8)) plt.rcParams.update({'font.size': 12}) sns.heatmap(correlation_matrix, cmap = 'viridis', vmin = -1, vmax = 1, center = 0, annot=True, fmt=".2f", square=True, linewidths=.5) plt.show()
🌐
Seaborn
seaborn.pydata.org › tutorial › color_palettes.html
Choosing color palettes — seaborn 0.13.2 documentation
The first two have a very wide luminance range and are well suited for applications such as heatmaps, where colors fill the space they are plotted into: sns.color_palette("rocket", as_cmap=True) sns.color_palette("mako", as_cmap=True) Because the extreme values of these colormaps approach white, they are not well-suited for coloring elements such as lines or points: it will be difficult to discriminate important values against a white or gray background.
🌐
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. For example, here is how to switch to the 'mako' color palette: sns.heatmap(dt_tweet_cnt, cmap="mako") plt.show() Seaborn provides many built-in palettes that you can choose from, but you should be careful to choose a good palette for your data and purpose.
🌐
Seaborn
seaborn.pydata.org › archive › 0.11 › generated › seaborn.heatmap.html
seaborn.heatmap — seaborn 0.11.2 documentation
>>> ax = sns.heatmap(flights, cmap="YlGnBu") Center the colormap at a specific value: >>> ax = sns.heatmap(flights, center=flights.loc["Jan", 1955]) Plot every other column label and don’t plot row labels: >>> data = np.random.randn(50, 20) >>> ax = sns.heatmap(data, xticklabels=2, yticklabels=False) Don’t draw a colorbar: >>> ax = sns.heatmap(flights, cbar=False) Use different axes for the colorbar: >>> grid_kws = {"height_ratios": (.9, .05), "hspace": .3} >>> f, (ax, cbar_ax) = plt.subplots(2, gridspec_kw=grid_kws) >>> ax = sns.heatmap(flights, ax=ax, ...
🌐
GeeksforGeeks
geeksforgeeks.org › data visualization › custom-color-palette-intervals-in-seaborn-heatmap
Custom Color Palette Intervals in Seaborn Heatmap - GeeksforGeeks
July 23, 2025 - Apply this custom color map to the heatmap. Python · import seaborn as sns import matplotlib.pyplot as plt import numpy as np from matplotlib.colors import LinearSegmentedColormap, BoundaryNorm # Generate some random data data = np.random.rand(10, 10) # Define custom colors colors = ["#d73027", "#f46d43", "#fdae61", "#fee08b", "#ffffbf", "#d9ef8b", "#a6d96a", "#66bd63", "#1a9850", "#006837"] cmap = LinearSegmentedColormap.from_list("custom", colors, N=100) # Define boundaries and corresponding colors boundaries = [0, 0.2, 0.4, 0.6, 0.8, 1.0] colors = ["#d73027", "#f46d43", "#fee08b", "#d9ef8b", "#66bd63"] cmap = LinearSegmentedColormap.from_list("custom", colors, N=len(colors)) norm = BoundaryNorm(boundaries, cmap.N, clip=True) # Create the heatmap with custom intervals sns.heatmap(data, cmap=cmap, norm=norm) plt.show() Output: Heatmap using Custom Color Palettes ·
🌐
Medium
medium.com › @chrisshaw982 › seaborn-correlation-heatmaps-customized-10246f4f7f4b
How to customize Seaborn Correlation Heatmaps | by Chris Shaw | Medium
February 3, 2019 - plt.figure(figsize=(5,5)) sns.heatmap(subjective.corr(), vmin=-1, cmap='coolwarm'); And the last readability tweak I usually do is to add the annotations for each of the correlations. With a small amount of features it doesn’t get too crowded but it can quickly get out of hand.
Find elsewhere
🌐
GeeksforGeeks
geeksforgeeks.org › python › seaborn-heatmap-a-comprehensive-guide
Seaborn Heatmap - A comprehensive guide - GeeksforGeeks
July 23, 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....
🌐
Seaborn
seaborn.pydata.org › archive › 0.12 › generated › seaborn.heatmap.html
seaborn.heatmap — seaborn 0.12.2 documentation
sns.heatmap(glue, cmap="crest") Or pass a colormap object: sns.heatmap(glue, cmap=sns.cubehelix_palette(as_cmap=True)) Set the colormap norm (data values corresponding to minimum and maximum points): sns.heatmap(glue, vmin=50, vmax=100) Use methods on the matplotlib.axes.Axes object to tweak the plot: ax = sns.heatmap(glue, annot=True) ax.set(xlabel="", ylabel="") ax.xaxis.tick_top()
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)

🌐
Statology
statology.org › home › how to make heatmaps with seaborn (with examples)
How to Make Heatmaps with Seaborn (With Examples)
January 18, 2021 - sns.heatmap(data, cmap="Spectral") Or we could choose the “coolwarm” color map: sns.heatmap(data, cmap="coolwarm") Find a complete list of cmap options available here.
🌐
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....
🌐
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()