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

标签 python matplotlib seaborn

我正在尝试创建一个顶部带有 xticklabel 的 Seaborn 热图(尝试使用条件格式模拟 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')

如何使 xticklabels 在每列上左对齐(而不是居中对齐)?我的 for 循环中的 x.set_ha='left' 似乎没有效果。

谢谢!

最佳答案

首先,set_ha是一个函数。您需要使用“left”参数调用它。

将刻度标签移动到热图顶部后,您还需要设置对齐方式:

# 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') 

关于python - 当刻度标签位于顶部时,Seaborn 热图 xticklabels 水平对齐不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53849734/

相关文章:

python c 扩展/opencl 守护进程

python - 是否有 python 方法来验证文件或 URL 的存在?

python - 在没有日期信息的条形图中绘制多天的数据

python - 如何在 Seaborn 的 Pairplot 中绘制右轴和上轴并删除左轴和下轴?

python seaborn重置回matplotlib

python - 在 DataFrame 中找到最频繁的组合

python - 如何将每个样本 1px 绘制到图像上?/DPI 测量的方向是什么?

python - 如何在不丢失数据的情况下将数据转换为图像

python - 使用数组填充 Seaborn 子图

python - 如何创建一个包含多变量函数值的 numpy 数组?