Goal: I want to create a heatmap from a dataframe which has 2 indexes. The 2nd index, called 'Profile_Name', is also used to loop through the dataframe to create several heatmaps.
Problem: The sns.heatmap does not allow me to change the values on the y axis.
code to recreate the dataframe
df = pd.DataFrame([['Monday', 1, 'Sebastian', 3],
['Monday', 2, 'Sebastian', 6],
['Monday', 3, 'Living room', 10],
['Tuesday', 1,'Sebastian', 6],
['Tuesday', 2,'Sebastian', 3],
['Tuesday', 3,'Sebastian', 8],
['Wednesday', 1,'Sebastian', 6],
['Wednesday', 2,'Sebastian', 3],
['Wednesday', 3,'Sebastian', 9],
['Tuesday', 1,'Living room', 6],
['Monday', 2,'Living room', 10]],
columns=['Weekday', 'Hour', 'Profile_Name', 'Counts'])
heatmap_df = df.pivot_table(index=('Hour', 'Profile_Name') ,columns='Weekday',values='Counts', aggfunc=lambda x:x).fillna(0)
heatmap_df.head()
The code to create the heatmaps
Names = df.Profile_Name.unique()
for Profile in Names:
plt.subplots(figsize=(15,10))
sns.heatmap(heatmap_df[heatmap_df.index.get_level_values('Profile_Name').isin([Profile])], annot= True, fmt='g', cmap="Blues")
plt.title(Profile, fontsize = 20) # title with fontsize 20
plt.xlabel('Weekday', fontsize = 15) # x-axis label with fontsize 15
plt.ylabel('Time', fontsize = 15) # y-axis label with fontsize 15
#ax.set_yticks(range(0,24)) ## doesnt work
plt.show()
How do I remove the second index 'Profile_Name', shown as 'Sebastian' in the screenshot, from the y axis? I want the y axis to only show the 'Hour' index or to completely overwrite it and set the values 0-23 on the y axis.
CodePudding user response:
The easiest fix is to drop the unneeded index from the dataframe (at the time of plotting). Alternatively, you could call ax.set_yticklabels(range(0,24), rotation=0)
if previously ax
has been given the correct value (either via fig, ax = plt.subplots(...)
or via ax = plt.gca()
. Such will only work if all 24 levels are present in the dataframe.