繁体   English   中英

Seaborn 热图上 y 轴刻度的垂直对齐

[英]Vertical alignment of y-axis ticks on Seaborn heatmap

我正在绘制Seaborn heatmap ,我想将y-axis刻度标签居中,但找不到方法来做到这一点。 yticks()上似乎没有'va'文本属性。

考虑下

在此处输入图片说明 我想将一周中的几天与一排方块的中心对齐

生成此图的代码

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

np.arange(7) +0.5添加到np.arange(7)对我plt.yticks

plt.yticks(np.arange(7)+0.5,('Mon','Tue','Wed','Thu','Fri','Sat','Sun'), rotation=0, fontsize="10", va="center")

onno 的解决方案适用于这种特定情况(矩阵类型的图通常在补丁中间有标签),但也可以考虑这些更通用的方法来帮助您:

a) 首先找出刻度线的位置

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

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

当然,您可以在更新期间直接使用这些职位:

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

b) 使用基于对象的 API 只调整文本

pyplot 命令xticks & yticks更新位置和文本。 但是轴对象具有独立的位置方法( ax.set_yticks(pos) )和文本( ax.set_yticklabels(labels) )。

只要您知道要生成多少标签(以及它们的顺序),您甚至不需要考虑它们的位置来更新文本。

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

这是一个老问题,但我最近遇到了这个问题,发现这对我有用:

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

当然,您也可以像在 OP 中那样定义labels=myLabelList

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM