Python matplotlib-如何在不调整热图大小的情况下移动色条?

2024-06-07 04:48:38 发布

您现在位置:Python中文网/ 问答频道 /正文

嗨,我有以下命令。

要在栅格中为热图指定子地块轴,请执行以下操作:

ax4 = plt.subplot2grid((3, 4), (1, 3), colspan=1, rowspan=1)

要在此轴上创建我的热图:

heatmap = ax4.pcolor(data, cmap=mycm, edgecolors = 'none', picker=True)

要将绘图向右移动,以便根据其他子块使其在轴上居中,请执行以下操作:

box = ax4.get_position()
ax4.set_position([box.x0*1.05, box.y0, box.width * 1.05, box.height])

显示不带填充的色条

fig.colorbar(heatmap, orientation="vertical")

然而,这会导致:

注意,色条在热图的顶部。

如果我使用pad关键字,我可以移动颜色条,使其不与热图重叠,但是这会减小绘图区域的宽度,即:

如何使绘图区域保持相同的宽度,并使颜色栏位于该区域之外?

谢谢!


Tags: 命令box区域绘图宽度颜色positionplt
1条回答
网友
1楼 · 发布于 2024-06-07 04:48:38

您可以放置colorbar into it's own axis并直接设置该轴的大小和位置。我在下面提供了一个示例,它在现有代码中添加了另一个轴。如果此图包含许多绘图和颜色栏,则可能需要使用gridspec将它们全部添加。

import matplotlib.pylab as plt
from numpy.random import rand

data = rand(100,100)
mycm = plt.cm.Reds

fig = plt.figure()
ax4 = plt.subplot2grid((3, 4), (1, 3), colspan=1, rowspan=1)

heatmap = ax4.pcolor(data, cmap=mycm, edgecolors = 'none', picker=True)

box = ax4.get_position()
ax4.set_position([box.x0*1.05, box.y0, box.width, box.height])

# create color bar
axColor = plt.axes([box.x0*1.05 + box.width * 1.05, box.y0, 0.01, box.height])
plt.colorbar(heatmap, cax = axColor, orientation="vertical")
plt.show()

enter image description here

相关问题 更多 >