15

I'm plotting a Seaborn heatmap and I want to center the y-axis tick labels, but can't find a way to do this. 'va' text property doesn't seem to be available on yticks().

Considering the following image

enter image description here I'd like to align the days of the week to the center of the row of squares

Code to generate this graph:

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

#Generate dummy data
startDate = '2017-11-25'
dateList = pd.date_range(startDate, periods=365).tolist()
df = pd.DataFrame({'Date': dateList,
                'Distance': np.random.normal(loc=15, scale=15, size=(365,))
              })
#set week and day
df['Week'] = [x.isocalendar()[1] for x in df['Date']]
df['Day'] = [x.isocalendar()[2] for x in df['Date']]

#create dataset for heatmap
#group by axis to plot
df = df.groupby(['Week','Day']).sum().reset_index()
#restructure for heatmap
data = df.pivot("Day","Week","Distance")

#configure the heatmap plot
sns.set()
fig, ax = plt.subplots(figsize=(15,6))
ax=sns.heatmap(data,xticklabels=1,ax = ax, robust=True, square=True,cmap='RdBu_r',cbar_kws={"shrink":.3, "label": "Distance (KM)"})
ax.set_title('Running distance', fontsize=16, fontdict={})

#configure the x and y ticks
plt.xticks(fontsize="9")
plt.yticks(np.arange(7),('Mon','Tue','Wed','Thu','Fri','Sat','Sun'), rotation=0, fontsize="10", va="center")

#set labelsize of the colorbar
cbar = ax.collections[0].colorbar
cbar.ax.tick_params(labelsize=10)

plt.show()
Chrisvdberge
  • 1,824
  • 6
  • 24
  • 46

3 Answers3

22

Adding +0.5 to np.arange(7) in the plt.yticks() worked for me

plt.yticks(np.arange(7)+0.5,('Mon','Tue','Wed','Thu','Fri','Sat','Sun'),
           rotation=0, fontsize="10", va="center")
MERose
  • 4,048
  • 7
  • 53
  • 79
onno
  • 969
  • 5
  • 9
8

onno's solution works for this specific case (matrix-type plots typically have labels in the middle of the patches), but also consider these more general ways to help you out:

a) find out where the ticks are first

pos, textvals = plt.yticks()
print(pos)

>>> [0.5 1.5 2.5 3.5 4.5 5.5 6.5]

and of course you can use these positions directly during the update:

plt.yticks(pos,('Mon','Tue','Wed','Thu','Fri','Sat','Sun'), 
    rotation=0, fontsize="10", va="center")

b) use the object-based API to adjust only the text

the pyplot commands xticks & yticks update both the positions and the text at once. But the axes object has independent methods for the positions (ax.set_yticks(pos)) and for the text (ax.set_yticklabels(labels)).

So long as you know how many labels to produce (and their order), you need not even think about their positions to update the text.

ax.set_yticklabels(('Mon','Tue','Wed','Thu','Fri','Sat','Sun'), 
    rotation=0, fontsize="10", va="center")
Shaido
  • 27,497
  • 23
  • 70
  • 73
Bonlenfum
  • 19,101
  • 2
  • 53
  • 56
5

This is an old question, but I recently had this issue and found this worked for me:

g = sns.heatmap(df)
g.set_yticklabels(labels=g.get_yticklabels(), va='center')

and of course you can just define labels=myLabelList also, as done in the OP

a11
  • 3,122
  • 4
  • 27
  • 66