Seaborn,更改colorbar的字体大小

17
我想要改变热力图颜色条的字体大小。
以下是我的代码:
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)来更改刻度标签,但是色条字体大小不会改变。 有没有办法做到这一点?

enter image description here

3个回答

34

你可以使用matplotlib.axes.Axes.tick_params和labelsize一起使用。

例如,你的图表使用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()

enter image description here

我参考了以下答案: - 使用matplotlib.colorbar.Colorbar对象 - 设置参数

5
我认为这应该是被接受的答案,因为它展示了如何独立于其他标签大小来更改色条标签大小,而不像Filipe Amaral的答案。 - laylaylom

9
您可以使用 seaborn.set() 方法来改变字体大小,只需将参数 font_scale 设置为您想要的大小即可。更多信息请查阅 seaborn 的文档。例如,您可以使用大小为 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()

plot with big font scale


6
这并不能真正解决问题,因为你正在改变所有标签的字体大小... - mortonjt
同意,但我不确定如何或是否可能仅更改一个标签的比例。如果这不能解决您的问题,很抱歉... - Filipe Amaral

-1

如果您设置了以下内容,它将使图表中的所有文本增加两倍。然而,如果您立即在此后设置 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)

别忘了把字体比例设置回去 :)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接