python - 如何防止颜色条随着热图高度变化而上下移动? Matplotlib/seaborn

标签 python matplotlib plot seaborn colorbar

我正在动态生成热图,y 轴和 x 轴上的类别数量每次可能不同。如何将颜色条放置在热图旁边,以便无论图形的高度如何,它始终固定在最顶部(基本上是热图的第一行)?

这是发生的事情:

enter image description here

enter image description here

到目前为止,我已经设法使用 add_axes 设置颜色条的高度和宽度,以便无论图形大小如何,它们都保持不变。然而,我正在努力动态设置其 y 轴位置。下面的最小示例:

import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable, axes_size

data = np.random.rand(5,5)

# Dynamic figure parameters.
topmargin = 0.1 
bottommargin = 0.1 
# Square height
cat_height = 0.4 
# Number of y-axis points.
n=data.shape[0]

leftmargin = 0.1
rightmargin = 0.1
# Square width.
cat_width = 0.5
# Number of x-axis points.
m=data.shape[1]

# Dynamic figure height.
figheight = topmargin + bottommargin + (n+1)*cat_height
# Dynamic figure width.
figwidth = leftmargin + rightmargin + (m+1)*cat_width

fig, ax = plt.subplots(figsize=(figwidth, figheight))

# [x, y, width, height]
cbar_ax = fig.add_axes([0.93, 0.33, 0.13/m, 2.75/n])

# Plot the heatmap.
ax = sns.heatmap(data, ax=ax, cmap='coolwarm', cbar_ax=cbar_ax, cbar=True)

plt.show()

基本上,当图形高度发生变化时,颜色条会向上/向下移动,但我希望它每次都固定在图形的顶部。

最佳答案

您可以根据 cbar 的高度和热图轴的顶部简单地计算底部坐标

cbar_ax = fig.add_axes([0.93, 0.88-2.75/n, 0.13/m, 2.75/n])

0.88 是具有默认边距的顶部子图的顶部(请参阅 plt.rcParams['figure.subplot.top'])。

但是,对于此类事情,我会使用 GridSpec 来定义具有可配置尺寸比率的轴网格(调整 height_ratios 以满足您的需求):

gs = matplotlib.gridspec.GridSpec(2,2, height_ratios=[3,n-3], width_ratios=[20,1])
fig = plt.figure(figsize=(figwidth, figheight))
ax = fig.add_subplot(gs[:,0])
cbar_ax = fig.add_subplot(gs[0,1])

关于python - 如何防止颜色条随着热图高度变化而上下移动? Matplotlib/seaborn,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56657661/

相关文章:

r - 设置开始、结束和频率后,将点添加到plot.ts

python - 使用 numpy 求多项式的根

python - GRASS 解析器()错误

python - 调用 re.compile 时什么属性返回正则表达式?

python - 使用带字典的 matplotlib 在 python 中绘制散点图

python - 使用 NetworkX 和 Matplotlib 促进网络增长

r - 如何将另一个数据集的折线图添加到已使用分面网格的现有折线图?

python - Django 的搜索功能

matplotlib - 在循环中使用 savefig() 时出现 IOError "Too many open files"

R 在设置宽度和高度的 PDF 中缩放绘图元素