调整海洋热图上子图的宽度

问题描述

遇到这个问题:Combining two heat maps in seaborn我做了以下事情:

df = pd.DataFrame(np.random.rand(8,1),columns=list("A"))
df2 = pd.DataFrame(np.random.rand(8,columns=list("B"))
df3 = pd.DataFrame(np.random.rand(8,4),columns=list("CDEF"))
df4 = pd.DataFrame(np.random.rand(8,columns=list("G"))
df5 = pd.DataFrame(np.random.rand(8,columns=list("H"))

fig,(ax,ax2,ax3,ax4,ax5) = plt.subplots(figsize=(30,10),ncols=5)
fig.subplots_adjust(wspace=0.01)

sb.heatmap(df,ax=ax,cbar=False,cmap = 'coolwarm_r',vmax = 30,vmin = 10,annot = True,fmt = '.2f',annot_kws = {'size':12})
sb.heatmap(df2,ax=ax2,vmax = 20,vmin = -10,annot_kws = {'size':12})
sb.heatmap(df3,ax=ax3,vmax = 50,vmin = 30,annot_kws = {'size':12})
sb.heatmap(df4,ax=ax4,vmax = 10,vmin = 5,annot_kws = {'size':12})
sb.heatmap(df5,ax=ax5,vmax = 8,vmin = 2,annot_kws = {'size':12})

ax2.set_yticks([])
ax3.set_yticks([])
ax4.set_yticks([])
ax5.set_yticks([])

ax.xaxis.tick_top()  # Put x axis on top
ax2.xaxis.tick_top()  # Put x axis on top
ax3.xaxis.tick_top()  # Put x axis on top
ax4.xaxis.tick_top()  # Put x axis on top
ax5.xaxis.tick_top()  # Put x axis on top

fig.colorbar(ax5.collections[0],location="right",use_gridspec=False,pad=0.2)
ax.tick_params(rotation=0)  # Do not rotate y tick labels

plt.show()

但是我得到以下输出,其中热图的每一列的宽度都不相同:

enter image description here

有什么方法可以调整每列的大小(包括中间一个df的那4列),以使它们的宽度都相同吗?

谢谢!

解决方法

也许我不完全理解您的问题,但是如何合并所有数据框并绘制热图呢?enter image description here

df_new = pd.concat([df,df2,df3,df4,df5],axis=1)

sb.heatmap(df_new,ax=ax,cbar=True,cmap = 'coolwarm_r',annot = True,fmt = '.2f',annot_kws = {'size':12})
,

'width_ratios'的{​​{1}}中的plt.subplot设置轴之间的比率。请注意,将颜色条添加到gridspec_kw将占用其一些空间,这将使其变小。因此,为颜色栏创建附加的ax5更为容易。由于轴彼此非常接近,因此可以添加虚拟轴以创建一些填充。 由于色标仅指ax,因此建议使用ax5删除它们。

使用循环可以更轻松地维护代码。

fig.colorbar(...,ticks=[])

example plot