您可以使用 x 轴变换来放置文本并绘制短线,使用 x 位置的数据坐标和 y 位置的轴坐标(0 在底部,1 在顶部)。默认情况下,文本不会被轴剪切,但其他元素会被剪切,所以它们需要clip_on=False
在主情节区域之外可见。
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
corr = np.corrcoef(np.random.randn(10, 20))
corr[np.triu_indices_from(corr)] = np.nan
sns.set_style("white")
ax = sns.heatmap(corr, vmax=.3, square=True, cmap="YlGnBu",
annot=True, fmt='.2f', cbar_kws={'pad': 0})
labels = ['Apples', 'Oranges', 'Pears', 'Bananas']
label_lens = [4, 2, 1, 3]
ax.set_xticks([]) # remove the x ticks
ax.set_yticks([]) # remove the y ticks
pos = 0
for label, label_len in zip(labels, label_lens):
if pos != 0:
ax.vlines(pos, pos, len(corr), color='r', lw=2)
ax.vlines(pos, 0, -0.02, color='r', lw=2,
transform=ax.get_xaxis_transform(), clip_on=False)
ax.hlines(pos, 0, pos, color='r', lw=2)
ax.hlines(pos, 0, -0.02, color='r', lw=2,
transform=ax.get_yaxis_transform(), clip_on=False)
ax.text(pos + label_len / 2, -0.02, label, ha='center', va='top',
transform=ax.get_xaxis_transform())
ax.text(-0.02, pos + label_len / 2, label, ha='right', va='center', rotation=90,
transform=ax.get_yaxis_transform())
pos += label_len
plt.tight_layout()
plt.show()