Thanks in advance for your help with my query. I would like to generate 4 heatmaps, the specialty is the row and colnum indicates the column in the facetgrid. Each heatmap should reflect the specialty and associated colnum. The final heatmap is called finalheatdf. I have more columns passed to sns.FacetGrid than I want for map_dataframe (Site on y axis and [‘0-2′,’11-12′,’3-4′,’5-6’] on the x axis). I am receiving an error ValueError: could not convert string to float: ‘X1’. My code is listed below
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import re
import numpy as np
waitremap = {'0-2':0,'3-4':1,'5-6':2,'7-8':3,'9-10':4,'11-12':5}
df = pd.DataFrame({ 'Spec':['A','A','A','B','B','B','A','B'],
'Wait':[5,6,2,4,1,2,11,12],
'Hosp':['X1','X2','X1','X2','X1','X2','X1','X2'],
'WaitClass':['5-6','5-6','0-2','3-4','0-2','0-2','11-12','11-12'],
#'specrow' :[1,1,1,2,2,2,1,2]
})
df = (df
.assign(waitindex = df.WaitClass.map(waitremap))
)
print(df)
heatdf = (pd.crosstab(index=[df.Hosp,df.Spec],columns=df.WaitClass,values=df.Wait,aggfunc='count',normalize='index')
.assign(colnum =1)
.reset_index()
)
print('********** heatdf *****************')
print(heatdf)
print('********** heatdf *****************')
heatdf1 = (pd.crosstab(index=[df.Hosp,df.Spec],columns=df.WaitClass,values=df.Wait,aggfunc='count',normalize=True)
.assign(colnum =2)
.reset_index()
)
finalheatdf = pd.concat([heatdf,heatdf1])
finalheatdf.index = finalheatdf.Hosp
print(finalheatdf)
print(finalheatdf.dtypes)
print(finalheatdf.index)
g3 = sns.FacetGrid(finalheatdf, col='colrow', row='Spec')
g3.map_dataframe(sns.heatmap)
Many Thanks
Steven
You can’t use sns.heatmap
directly since it has the extra non-numeric columns, you should use a wrapper to only select the needed columns to pass to heatmap
:
def heatmap(*args, **kwargs):
sns.heatmap(kwargs['data'].drop(columns=kwargs['drop'], errors='ignore'))
g3 = sns.FacetGrid(finalheatdf.drop(columns='Hosp'), col='colnum', row='Spec')
g3.map_dataframe(heatmap, drop=['colnum', 'Spec'])
Or pass a list of columns to keep:
def heatmap(*args, **kwargs):
sns.heatmap(kwargs['data'].reindex(columns=kwargs['cols']))
g3 = sns.FacetGrid(finalheatdf.drop(columns='Hosp'), col='colnum', row='Spec')
g3.map_dataframe(heatmap, cols=['0-2', '11-12', '3-4', '5-6'])
NB. you could make a generic function that accepts either case.
Output:
1