MitchellFletcher001
MitchellFletcher001

Reputation: 11

Converting a matplotlib colourmap to a seaborn colour palette

I have made a colourmap from my chosen colours, however I'd like to convert it to a palette which can be used to 'hue' a seaborn plot. Is this possible, and if so how so?

I have used...

cmap = pl.colors.LinearSegmentedColormap.from_list("", ["red","white"],gamma=0.5,N=len(hue))

...in order to make my own colourmap, which I know works because it can be applied to a standard matplotlib.pyplot.scatter plot successfully, as shown below.

plt.scatter(x=[1,2,3,4,5],y=[1,2,3,4,5],c=[5,4,3,2,1],cmap=cmap)

click here to see the output as it won't let me embed an image

However, I am trying to use seaborn's swarmplot function and pass in my colourmap as the hue parameter. Obviously this doesn't work as this parameter requires a palette - hence my question!

I'm not quite sure where to start! Any help would be appreciated!

Upvotes: 1

Views: 1034

Answers (1)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339112

A seaborn palette is a simple list of colors. You may obtain the colors via

cmap(np.linspace(0,1,cmap.N))

Complete example:

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

df  =pd.DataFrame({"x" : np.random.randint(0,4, size=200),
                   "y" : np.random.randn(200),
                   "hue" : np.random.randint(0,4, size=200)})

u = np.unique(df["hue"].values)
cmap = mcolors.LinearSegmentedColormap.from_list("", ["indigo","gold"],gamma=0.5,N=len(u))

sns.swarmplot("x", "y", hue="hue", data=df, palette=cmap(np.linspace(0,1,cmap.N)))

plt.show()

enter image description here

Upvotes: 3

Related Questions