Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pandas and seaborn - heatmap with no colors

I've been working with seaborn and its heatmap function. I would like to build a matrix with annotated values from pandas dataframe df:

C,L,N
a,x,10
a,y,2
a,z,4
b,x,1
b,y,22
b,z,11
c,x,3
c,y,1
c,z,0

So far it worked fine with:

# Read DataBase
df = pd.read_csv('myfile.csv')

# Save Users/City/Language Matrix
pdf = df.pivot(index='C',columns='L',values='N').fillna(0)

# Set Font Parameters
rc = {'font.size': 8, 'xtick.labelsize': 11, 'ytick.labelsize': 11}

# Set Figure
fig = plt.figure(figsize=(20, 9))

# Assign to Seaborn
sns.set(rc=rc)

with sns.axes_style('white'):

    sns.heatmap(pdf,
                cbar=False,
                square=False,
                annot=True,
                cmap='Blues',
                fmt='g',
                linewidths=0.5)

Which returns:

enter image description here

At the end I'm interested to keep only the values and save the structure as a simple table, discarding the colors. I tried to set cmap=None but it doesn't work, and without the cmap, seaborn assigns a default cmap to the heatmap.

like image 701
Fabio Lamanna Avatar asked Dec 15 '22 09:12

Fabio Lamanna


1 Answers

If I didn't understand you wrong, and all you want is to ignore the colormap, you can create your custom colormap with the background color of your choice using matplotlib's ListedColormap:

from matplotlib.colors import ListedColormap

with sns.axes_style('white'):
    sns.heatmap(pdf,
                cbar=False,
                square=False,
                annot=True,
                fmt='g',
                cmap=ListedColormap(['white']),
                linewidths=0.5)

Which will yield:

enter image description here

Replace the string white with a STR, HEX or RGB color to set up the background color of your choice.

However, I believe pandas offers better export options. Find bellow a screen of all the possible export options:

enter image description here

Depending where you want to insert the table, maybe to_html, to_json or to_latex are better options than plotting with seaborn.

like image 184
Imanol Luengo Avatar answered Dec 29 '22 12:12

Imanol Luengo