对热图的刻度线进行分组

2024-03-12

I have a heatmap that looks like this (from: Plotting a 2D heatmap with Matplotlib https://stackoverflow.com/questions/33282368/plotting-a-2d-heatmap-with-matplotlib). enter image description here

我正在尝试创建一个热图,该热图没有每个值的刻度标签,而是按范围分组。例如,前三个刻度线尚未签名,但已与一个联合签名“Apples”一起签名。

使用以下命令似乎很容易禁用刻度标签:

plt.tick_params(
    axis='x',
    which='both',
    bottom=False,
    top=False,
    labelbottom=False)

或仅选择选定的刻度:

for (i,l) in enumerate(ax.xaxis.get_ticklabels()):
    if i == 0 or i == 4 or i == 5:
        l.set_visible(True)
    else:
        l.set_visible(False) 

但可以按如下方式完成吗?

热图的示例代码:

corr = np.corrcoef(np.random.randn(10, 200))
mask = np.zeros_like(corr)
mask[np.triu_indices_from(mask)] = True
with sns.axes_style("white"):
    ax = sns.heatmap(corr, mask=mask, vmax=.3, square=True,  cmap="YlGnBu")
    plt.show()

您可以使用 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()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

对热图的刻度线进行分组 的相关文章

随机推荐