heatmap - 将水平颜色条的大小与 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")
如何将颜色条的大小与热图的大小相匹配?
解决方案
您可以使用我的回答中的第二个或第三个选项来定位 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()
推荐阅读
- android - Android SQLiteCantOpenDatabaseException
- c# - 如何在 Autodesk Inventor 中创建插件?
- python - 在 Python 中缩短冗长且重复的方程式
- sql - 在伪列名上使用 Rank()
- python - 如何在 x 轴上显示日期时间?
- wordpress - 想要通过在 WORDPRESS 中添加 URL 来编辑结帐页面
- acumos - 数据管道不可用
- c++ - 如何将 time-uuid(存储在 boost uuid 中)转换为自纪元以来的时间戳/时间?
- java - 带有 Android 查询的房间。此查询在另一个 SQLite 浏览器中工作,但在 Android 中不工作
- laravel - 将上传的文件移动到 root/public_html