Seaborn 热图更改颜色条的大小

Seaborn heatmap change size of colorbar

我使用以下代码绘制了一个 seaborn 热图和一个颜色条。 我想将颜色条的大小设置为等于热图的大小。 我怎样才能做到这一点?

我尝试使用 fig.colorbar(heatmap) 来处理颜色条,但是 returns 错误:

AttributeError: 'AxesSubplot' object has no attribute 'autoscale_None'

代码:

fig,ax=plt.subplots(figsize=(30,60))

cmap = plt.get_cmap('inferno',30)
cmap.set_under('white')#Colour values less than vmin in white
cmap.set_over('yellow')# colour valued larger than vmax in red 

Crosstab=50000*np.random.randn(10,10)

heatmap=sns.heatmap(Crosstab[::-1],cmap=cmap,annot=False,square=True,ax=ax,vmin=1,vmax=50000,linewidths=0.8,linecolor="grey")



plt.show()

如评论中所述,我无法使用 Seaborn 版本 0.8 和 matplotlib 2.1.1 重现此问题,因此如果可能,我建议更新模块。

也就是说,您可以使用 seaborn.heatmap. This needs to be a dictionary which is passed (under the hood) as kwargs to matplotlibs fig.colorbar() 中的 cbar_kws 参数来控制颜色条的大小。

一个有趣的参数是 shrink 参数。这会缩小颜色条的大小:

shrink: 1.0; fraction by which to multiply the size of the colorbar

默认值 应该 为 1.0,因此您可以尝试手动将其设置为 1。但是,如果这不起作用,您可以使用较低的值进一步缩小颜色栏。这可能需要一些修改才能使颜色栏大小合适。

fig, ax = plt.subplots()

cmap = plt.get_cmap('inferno',30)
cmap.set_under('white')#Colour values less than vmin in white
cmap.set_over('yellow')# colour valued larger than vmax in red

Crosstab=50000*np.random.randn(10,10)

heatmap=sns.heatmap(Crosstab[::-1],cmap=cmap,annot=False,square=True,ax=ax,vmin=1,vmax=50000,
                    cbar_kws={"shrink": 0.5},linewidths=0.8,linecolor="grey")

plt.show()

给予:

我觉得你的问题出在身材比例上。而不是声明...

fig, ax = plt.subplots(figsize=(30,60))

...尝试保持比例均匀:

fig, ax = plt.subplots(figsize=(30,30))

这对我有用。

跟进 DavidG 非常有用的回答和 Yuca 的问题(抱歉,我无法发表评论):

如果您有多个 cbar_kws,通过由名称=值对构造的字典提供 cbar_kws 会很有用。

例如我用于 seaborn 热图的常见 cbar_kws 字典:

cbar_kws=dict(use_gridspec=False,location="bottom",pad=0.01,shrink=0.25)

在这里,Yuca 可以执行以下操作来缩小 cbar 并更改填充(尝试几个填充值以查看哪个看起来最好): `cbar_kws=dict(shrink=0.5,pad=0.01)