问题描述
如何更改Seaborn的热图垂直色条的刻度标签的位置和大小?
我尝试了以下代码
ax.figure.axes[-1].yaxis.label.set_size(36)
ax.figure.axes[-1].yaxis.label.set_position((4,1.0))
但是,这是行不通的,即颜色条刻度标记的字体大小保持在相同位置且字体大小相同。我也在做
colorbar = ax.collections[0].colorbar
colorbar.set_ticks([-0.667,0.667])
# I want these labels to be bigger and more to the right!!
colorbar.set_ticklabels(['-1','0','1'])
使用colorbar.set_ticks([-0.667,0.667])
,我可以更改刻度的垂直位置,但我也希望关联的标签离刻度本身更远。
解决方法
由于需要通过colorbar.set_ticks()
设置位置,所以颜色条的刻度有些混乱,但是如果要更改其他参数,则必须返回到基础轴。对于垂直彩条,使用y轴。
This post显示了一种使颜色条始终与主图相同的高度的方法。必须在sns.heatmap
外部创建颜色栏。
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
import numpy as np
import seaborn as sns
ax = sns.heatmap(np.random.uniform(-.6,.6,(6,12)),cmap='inferno',vmin=-0.667,vmax=0.667,square=True,cbar=False)
divider = make_axes_locatable(ax)
cax = divider.append_axes("right",size="5%",pad=0.1)
cbar = plt.colorbar(ax.collections[0],cax=cax)
cbar.set_ticks([-0.667,0.667])
cbar.ax.set_yticklabels(['-1','0','1'],size=20)
cbar.ax.tick_params(axis='y',which='major',length=0,pad=15)
cbar.outline.set_edgecolor('black')
cbar.outline.set_linewidth(2)
plt.tight_layout()
plt.show()