Seaborn,更改颜色条的字体大小

Seaborn, change font size of the colorbar

我想更改热图颜色栏的字体大小。

以下是我的代码:

import seaborn as sns
import matplotlib.pyplot as plt
from numpy import arange
x = arange(25).reshape(5, 5)
cmap = sns.diverging_palette(220, 20, sep=20, as_cmap=True)
ax = sns.heatmap(x, cmap=cmap)
plt.show()

我能够使用 plt.tick_params(axis='both', labelsize=20) 更改刻度标签。但是,颜色条字体大小不会改变。 有办法吗?

您可以使用 seaborn.set() 方法更改字体比例,将 font_scale 参数设置为您想要的比例,在 seaborn documentation.

中查看更多信息

例如,比例尺为 3 的图:

import seaborn as sns
import matplotlib.pyplot as plt
from numpy import arange
# here set the scale by 3
sns.set(font_scale=3)
x = arange(25).reshape(5, 5)
cmap = sns.diverging_palette(220, 20, sep=20, as_cmap=True)
ax = sns.heatmap(x, cmap=cmap)
plt.show()

您可以将 matplotlib.axes.Axes.tick_params 与 labelsize 结合使用。

例如,标签大小为 20 的绘图:

import seaborn as sns
import matplotlib.pyplot as plt
from numpy import arange
x = arange(25).reshape(5, 5)
cmap = sns.diverging_palette(220, 20, sep=20, as_cmap=True)
ax = sns.heatmap(x, cmap=cmap)
# use matplotlib.colorbar.Colorbar object
cbar = ax.collections[0].colorbar
# here set the labelsize by 20
cbar.ax.tick_params(labelsize=20)
plt.show()

我参考了下面的回答:
-
-

如果您设置以下内容,它会将图表中的所有文本增加两倍。但是,如果您立即将 tick_params 设置为右下角,您将只剩下颜色栏的字体大小增加。

sns.set(font_scale=2)

sns.heatmap(df, vmin=0, vmax=1, center=0.5)

heatmap.tick_params(labelsize=15)

sns.set(font_scale=1)

不要忘记设置 font_scale :)