当刻度标签在顶部时,Seaborn热图xticklabels水平对齐不起作用

时间:2018-12-19 10:54:49

标签: python matplotlib seaborn

我正在尝试创建一个顶部带有xticklabel的Seaborn Heatmap(以尝试使用条件格式模拟Excel表)。

我正在使用的代码如下:

plt.figure(figsize=[12, 6])
ax = sns.heatmap(df, vmin=1, vmax=149, cmap=cmap_RdYlGn_r, cbar=False, fmt='s')

# Each pair of columns is a rank / value. Hide the label for one of these
ticklbls = ax.get_xticklabels(which='both')
for x in ticklbls:
    x.set_ha='left' #### This has no effect
    if '[raw value]' in x.get_text():
        x.set_text('')
    elif '[rank]' in x.get_text():
        x.set_text('\n'.join(wrap(x.get_text(), 30)))
ax.set_xticklabels(ticklbls)

# Put the xticklabels at the top of the heatmap
ax.tick_params(axis='x', top=False, labeltop=True, labelbottom=False, direction='out')

如何使xticklabel在每一列上保持对齐(而不是居中对齐)?我的for循环中的x.set_ha='left'似乎无效。

谢谢!

1 个答案:

答案 0 :(得分:1)

Firstly, set_ha is a function. You need to call it with the argument of 'left'.

You also need to set the alignment after you move the tick labels to the top of the heatmap:

# Put the xticklabels at the top of the heatmap
ax.tick_params(axis='x', top=False, labeltop=True, labelbottom=False, direction='out')

ticklbls = ax.get_xticklabels(which='both')

for x in ticklbls:
    x.set_ha('left') 
相关问题