Python Matplotlib-如何在不调整热图大小的情况下移动颜色栏? [英] Python matplotlib - how to move colorbar without resizing the heatmap?

查看:348
本文介绍了Python Matplotlib-如何在不调整热图大小的情况下移动颜色栏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下命令.

要在网格中为热图指定子图轴:

To specify a subplot axes in the grid for the heatmap:

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

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

To create my heatmap in this axes:

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

要根据其他子图将图向右移动以使其在轴中居中

To move the plot to the right in order to center it in the axes according to other subplots:

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

要显示没有填充的颜色条

To show the colorbar with no padding

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

但这会导致:

请注意,颜色栏位于热图的顶部.

Notice the colorbar is on top of the heatmap.

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

If I use the pad keyword I can move the colorbar so it doesn't overlap with the heatmap, however this reduces the width of the plotting area i.e.:

如何使打印区域具有相同的宽度,而使颜色栏位于该区域之外?

How can I keep the plotting area the same width and just have the colorbar outside of this area?

谢谢!

推荐答案

您可以将颜色栏放入其自身的轴中并直接设置该轴的大小和位置.我在下面提供了一个示例,该示例将另一个轴添加到您的现有代码中.如果该图包含许多图和颜色条,则可能需要使用 gridspec 将它们全部添加.

You can put the colorbar into it's own axis and set the size and position of that axis directly. I've included an example below that adds another axis to your existing code. If this figure includes many plots and color bars you might want to add them all using 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()

这篇关于Python Matplotlib-如何在不调整热图大小的情况下移动颜色栏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆