首页 > 解决方案 > 将水平颜色条的大小与 Seaborn 中方形热图的宽度相匹配

问题描述

我想用下面的颜色条在 Seaborn 中生成一个方形热图。这是我正在使用的代码:

#!/usr/bin/env python3

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}
f, (ax, cbar_ax) = plt.subplots(2, 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")

这是输出: 输出

如何将颜色条的大小与热图的大小相匹配?

标签: heatmapseaborncolorbar

解决方案


您可以使用我的回答中的第二个或第三个选项来定位 colorbar。因为在 seaborn 情节的情况下如何做到这一点可能并不明显。

使用子图

可以直接创建两行子图,一行用于图像,另一行用于颜色条,就像问题中所做的那样,只需要确保图形大小水平挤压绘图,而不是垂直挤压绘图。在这种情况下,请尝试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()

在此处输入图像描述


推荐阅读