关于python:Seaborn heatmap-颜色条标签字体大小

Seaborn heatmap - colorbar label font size

如何设置颜色条标签的字体大小?

1
2
ax=sns.heatmap(table, vmin=60, vmax=100, xticklabels=[4,8,16,32,64,128],yticklabels=[2,4,6,8], cmap="PuBu",linewidths=.0,
        annot=True,cbar_kws={'label': 'Accuracy %'}

enter image description here


不幸的是,seaborn无法访问其创建的对象。 因此,需要绕道而行,因为颜色条是当前图形中的一个轴,并且它是最后一个创建的轴,因此

1
2
ax = sns.heatmap(...)
cbar_axes = ax.figure.axes[-1]

对于此轴,我们可以通过使用其set_size方法获取ylabel来设置字体大小。

例如,将fontsize设置为20磅:

1
2
3
4
5
6
7
8
import matplotlib.pyplot as plt
import numpy as np; np.random.seed(0)
import seaborn as sns
data = np.random.rand(10, 12)*100
ax = sns.heatmap(data, cbar_kws={'label': 'Accuracy %'})
ax.figure.axes[-1].yaxis.label.set_size(20)

plt.show()

enter image description here

请注意,当然可以通过

1
2
ax = sns.heatmap(data)
ax.figure.axes[-1].set_ylabel('Accuracy %', size=20)

没有传递关键字参数。


您还可以显式将axis对象传递到heatmap并直接对其进行修改:

1
2
3
4
grid_spec = {"width_ratios": (.9, .05)}
f, (ax, cbar_ax) = plt.subplots(1,2, gridspec_kw=grid_spec)
sns.heatmap(data, ax=ax, cbar_ax=cbar_ax, cbar_kws={'label': 'Accuracy %'})
cbar_ax.yaxis.label.set_size(20)