Python matplotlib - how to move colorbar without resizing the heatmap?

拟墨画扇 提交于 2019-12-10 10:19:38

问题


Hi so I have the following commands.

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")

However this results in:

Notice the colorbar is on top of the heatmap.

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?

Thanks!


回答1:


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()



来源:https://stackoverflow.com/questions/19679409/python-matplotlib-how-to-move-colorbar-without-resizing-the-heatmap

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!