Codedorf
Codedorf

Reputation: 121

How can I convert a seaborn color palette into a cmap?

I would like to convert the continuous diverging color palette "RdBu_r" (or really, any pre-defined color palette) in seaborn into a matplotlib colormap.

This is the closest I've come, but it creates a discrete color map, whereas I would like a continuous map:

import seaborn as sns
from matplotlib.colors import ListedColormap

palette = sns.color_palette("RdBu_r", n=7) # could make n = 100 as a quick fix
cmap = ListedColormap(colors=palette)
cmap.set_bad(color='black', alpha=0.5)
sns.heatmap(cmap=cmap) 

Ultimately, I am trying to create a seaborn heatmap with the "RdBu_r" color palette, with null values filled in as dark squares, which is why I am trying to create a cmap with set_bad(color='black'), as opposed to just passing in "RdBu_r" into the cmap argument of sns.heatmap.

Thanks guys.

Upvotes: 2

Views: 3647

Answers (1)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339250

"RdBu_r" is a matplotlib colormap. There hence seems little reason to convert it to a list of colors first. Instead just use it as it is.

import matplotlib.pyplot as plt
import seaborn as sns

cmap = plt.get_cmap("RdBu_r")
cmap.set_bad(color='black', alpha=0.5)

sns.heatmap(data, cmap=cmap) 

Upvotes: 3

Related Questions