Vertical alignment of y-axis ticks on Seaborn heatmap

非 Y 不嫁゛ 提交于 2021-02-18 16:41:10

问题


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

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()

回答1:


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")



回答2:


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")


来源:https://stackoverflow.com/questions/53295967/vertical-alignment-of-y-axis-ticks-on-seaborn-heatmap

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!