您可以使用第二个或第三个选项
my answer
到
positioning the colorbar
。因为对于一个海生的阴谋来说,如何做到这一点并不明显。
使用子批次
我们可以直接创建两行子图,一行用于图像,另一行用于颜色栏,正如在问题中所做的那样,我们只需要确保图形大小水平挤压绘图,而不是垂直挤压绘图。在这种情况下,尝试
figsize=(3,5)
.
import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt
data = np.random.rand(5,4)
grid_kws = {"height_ratios": (.9, .05), "hspace": .5}
fig, (ax, cbar_ax) = plt.subplots(2, figsize=(3,5), gridspec_kw=grid_kws)
ax = sns.heatmap(data,
ax=ax,
cbar_ax=cbar_ax,
annot=True,
square=True,
cbar_kws={ "orientation": "horizontal" })
#plt.savefig("heatmap.png")
plt.show()
使用轴分割器
import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
data = np.random.rand(5,4)
fig, ax = plt.subplots()
divider = make_axes_locatable(ax)
cbar_ax = divider.new_vertical(size="5%", pad=0.5, pack_start=True)
fig.add_axes(cbar_ax)
ax = sns.heatmap(data,
ax=ax,
cbar_ax=cbar_ax,
annot=True,
square=True,
cbar_kws={ "orientation": "horizontal" })
#plt.savefig("heatmap.png")
plt.show()