Question

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!

Was it helpful?

Solution

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

enter image description here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top