Relabel axis ticks in seaborn heatmap

流过昼夜 提交于 2021-02-11 13:33:00

问题


I have a seaborn heatmap that I am building from a matrix of values. 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. 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.


回答1:


You are setting the x and y tick labels of the axis you have just created. You are then plotting the seaborn heatmap which will overwrite the tick labels you have just set.

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)


来源:https://stackoverflow.com/questions/52314599/relabel-axis-ticks-in-seaborn-heatmap

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!