首页 > 解决方案 > 在 Seaborn 图中对齐多行刻度

问题描述

我有以下热图:

在此处输入图像描述

我已经按每个大写字母分解了类别名称,然后将它们大写。默认情况下,这在我的 x 轴上的标签上实现了居中效果,我想在我的 y 轴上复制它。

yticks = [re.sub("(?<=.{1})(.?)(?=[A-Z]+)", "\\1\n", label, 0, re.DOTALL).upper() for label in corr.index]
xticks = [re.sub("(?<=.{1})(.?)(?=[A-Z]+)", "\\1\n", label, 0, re.DOTALL).upper() for label in corr.columns]
fig, ax = plt.subplots(figsize=(20,15))
sns.heatmap(corr, ax=ax, annot=True, fmt="d",
            cmap="Blues", annot_kws=annot_kws,
            mask=mask, vmin=0, vmax=5000,
            cbar_kws={"shrink": .8}, square=True,
            linewidths=5)
for p in ax.texts:
    myTrans = p.get_transform()
    offset = mpl.transforms.ScaledTranslation(-12, 5, mpl.transforms.IdentityTransform())
    p.set_transform(myTrans + offset)
plt.yticks(plt.yticks()[0], labels=yticks, rotation=0, linespacing=0.4)
plt.xticks(plt.xticks()[0], labels=xticks, rotation=0, linespacing=0.4)

其中corr表示预定义的 pandas 数据框。

我似乎找不到align用于设置刻度的参数,并且想知道是否以及如何在 seaborn/matplotlib 中实现这种居中?

标签: matplotlibseaborn

解决方案


我已经改编了下面的 seaborn 相关图示例。

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

sns.set_theme(style="white")

# Generate a large random dataset
rs = np.random.RandomState(33)
d = pd.DataFrame(data=rs.normal(size=(100, 7)),
                 columns=['Donald\nDuck','Mickey\nMouse','Han\nSolo',
                          'Luke\nSkywalker','Yoda','Santa\nClause','Ronald\nMcDonald'])

# Compute the correlation matrix
corr = d.corr()

# Generate a mask for the upper triangle
mask = np.triu(np.ones_like(corr, dtype=bool))

# Set up the matplotlib figure
f, ax = plt.subplots(figsize=(11, 9))

# Generate a custom diverging colormap
cmap = sns.diverging_palette(230, 20, as_cmap=True)

# Draw the heatmap with the mask and correct aspect ratio
sns.heatmap(corr, mask=mask, cmap=cmap, vmax=.3, center=0,
            square=True, linewidths=.5, cbar_kws={"shrink": .5})

for i in ax.get_yticklabels():
    i.set_ha('right')
    i.set_rotation(0)
    
for i in ax.get_xticklabels():
    i.set_ha('center')

请注意上面的两个序列。这些获取标签,然后设置水平对齐方式(您也可以更改垂直对齐方式 ( set_va())。

上面的代码产生了这个:

示例图


推荐阅读