seaborn color_palette as matplotlib colormap

PythonMatplotlibPlotSeaborn

Python Problem Overview


Seaborn offers a function called color_palette, which allows you to easily create new color_palettes for plots.

colors = ["#67E568","#257F27","#08420D","#FFF000","#FFB62B","#E56124","#E53E30","#7F2353","#F911FF","#9F8CA6"]
    
color_palette = sns.color_palette(colors)

I want to transform color_palette to a cmap, which I can use in matplotlib, but I don't see how I can do this.

Sadly just functions like "cubehelix_palette","light_palette",… have an "as_cmap" paramater. "color_palette" doesn't, unfortunately.

Python Solutions


Solution 1 - Python

You have to convert a list of colors from seaborn palette to color map of matplolib (thx to @RafaelLopes for proposed changes):

import seaborn as sns
import matplotlib.pylab as plt
import numpy as np
from matplotlib.colors import ListedColormap

# construct cmap
flatui = ["#9b59b6", "#3498db", "#95a5a6", "#e74c3c", "#34495e", "#2ecc71"]
my_cmap = ListedColormap(sns.color_palette(flatui).as_hex())

N = 500
data1 = np.random.randn(N)
data2 = np.random.randn(N)
colors = np.linspace(0,1,N)
plt.scatter(data1, data2, c=colors, cmap=my_cmap)
plt.colorbar()
plt.show()

enter image description here

Solution 2 - Python

Most seaborn methods to generate color palettes have an optional argument as_cmap which by default is False. You can use to directly get a Matplotlib colormap:

import seaborn as sns
import matplotlib.pylab as plt
import numpy as np

# construct cmap
my_cmap = sns.light_palette("Navy", as_cmap=True)

N = 500
data1 = np.random.randn(N)
data2 = np.random.randn(N)
colors = np.linspace(0,1,N)
plt.scatter(data1, data2, c=colors, cmap=my_cmap)
plt.colorbar()
plt.show()

enter image description here

Solution 3 - Python

The first answer is somehow correct but way too long with a lot of unnecessary information. The correct and short answer is:

To convert any sns.color_palette() to a matplotlib compatible cmap you need two lines of code

from matplotlib.colors import ListedColormap
cmap = ListedColormap(sns.color_palette())

Solution 4 - Python

Just an additional tip - if one wants a continuous colorbar/colormap, adding 256 as the number of colors required from Seaborn colorscheme helps a lot.

cmap = ListedColormap(sns.color_palette("Spectral",256))   

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDremetView Question on Stackoverflow
Solution 1 - PythonSerenityView Answer on Stackoverflow
Solution 2 - PythonRamon CrehuetView Answer on Stackoverflow
Solution 3 - PythonGeneric WeversView Answer on Stackoverflow
Solution 4 - PythonLauraDView Answer on Stackoverflow