我正在尝试创建一个顶部带有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'
似乎无效。
谢谢!
答案 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')