简体   繁体   English

在seaborn热图中重新标记轴刻度

[英]Relabel axis ticks in seaborn heatmap

I have a seaborn heatmap that I am building from a matrix of values.我有一个由值矩阵构建的 seaborn 热图。 Each element of the matrix corresponds to an entitiy that I would like to make the tick label for each row/col in the matrix.矩阵的每个元素对应一个实体,我想为矩阵中的每一行/列制作刻度标签。

I tried using the ax.set_xticklabel() function to accomplish this but it seems to do nothing.我尝试使用ax.set_xticklabel()函数来完成此操作,但似乎什么也没做。 Here is my code:这是我的代码:

type(jr_matrix)
>>> numpy.ndarray

jr_matrix.shape
>>> (15, 15)

short_cols = ['label1','label2',...,'label15'] # list of strings with len 15

fig, ax = plt.subplots(figsize=(13,10)) 
ax.set_xticklabels(tuple(short_cols)) # i also tried passing a list
ax.set_yticklabels(tuple(short_cols))
sns.heatmap(jr_matrix, 
            center=0, 
            cmap="vlag", 
            linewidths=.75, 
            ax=ax,
            norm=LogNorm(vmin=jr_matrix.min(), vmax=jr_matrix.max()))

The still has the matrix indices as labels:仍然有矩阵索引作为标签:

在此处输入图片说明

Any ideas on how to correctly change these labels would be much appreciated.任何关于如何正确更改这些标签的想法将不胜感激。

Edit: I am doing this using jupyter notebooks if that matters.编辑:如果重要的话,我正在使用 jupyter notebooks 来做这件事。

You are setting the x and y tick labels of the axis you have just created.您正在设置刚刚创建的轴的 x 和 y 刻度标签。 You are then plotting the seaborn heatmap which will overwrite the tick labels you have just set.然后您正在绘制 seaborn 热图,它将覆盖您刚刚设置的刻度标签。

The solution is to create the heatmap first, then set the tick labels:解决方案是先创建热图,然后设置刻度标签:

fig, ax = plt.subplots(figsize=(13,10)) 

sns.heatmap(jr_matrix, 
            center=0, 
            cmap="vlag", 
            linewidths=.75, 
            ax=ax,
            norm=LogNorm(vmin=jr_matrix.min(), vmax=jr_matrix.max()))

# passing a list is fine, no need to convert to tuples
ax.set_xticklabels(short_cols)
ax.set_yticklabels(short_cols)

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

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