2
votes

I plot two figures using gridspec:

fig = plt.figure(num=2,figsize=(5,2))
gs = gridspec.GridSpec(1, 2, width_ratios=[1,1])
ax0 = plt.subplot(gs[0])
ax1 = plt.subplot(gs[1])

ax0.imshow(ROI,'gray')

map1 = ax1.imshow(z,cmap=cm.YlOrRd)
divider1 = make_axes_locatable(ax1)  
cax1 = divider1.append_axes("right", size="5%", pad=0.05)
cbar1 = plt.colorbar(map1, cax=cax1)

ROI and z are pre-defined with the same size. But they resutl in slightly different sizes.

I want to make it as a same size:

enter image description here

How can this be fixed?

1
I cannot reproduce this behaviour -- can you please provide a Minimal, Complete, and Verifiable example. - Thomas Kühn

1 Answers

2
votes

The problem is that you fix the width of the two figures to be the same in gridspec and then add the colorbar to the second plot which takes up some of the width (5% plus the padding). And as imshow has an 1:1 aspect ration this change of width also changes the height of the figure.

The simplest way to avoid that is to account for the additional width of the colorbar in the width ratio:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
from mpl_toolkits.axes_grid1 import make_axes_locatable

# Random test data:
ROI = np.random.rand(250, 150)
z = np.random.rand(250, 150)

fig = plt.figure(num=2,figsize=(4,2))
gs = gridspec.GridSpec(1, 2, width_ratios=[1,1.08])
ax0 = plt.subplot(gs[0])
ax1 = plt.subplot(gs[1])

ax0.imshow(ROI,'gray')

map1 = ax1.imshow(z,cmap=plt.cm.YlOrRd)
divider1 = make_axes_locatable(ax1)
cax1 = divider1.append_axes("right", size="5%", pad="3%")
cbar1 = plt.colorbar(map1, cax=cax1)

plt.show()

This will result in the following plot:

enter image description here

You can also avoid that by simply adding a third axes for the colorbar using gridspec:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

# Random test data:
ROI = np.random.rand(250, 150)
z = np.random.rand(250, 150)

fig = plt.figure(num=2,figsize=(5,2))
gs = gridspec.GridSpec(1, 3, width_ratios=[1,1,0.05])
ax0 = plt.subplot(gs[0])
ax1 = plt.subplot(gs[1])
cax1 = plt.subplot(gs[2])

ax0.imshow(ROI,'gray')
map1 = ax1.imshow(z,cmap=plt.cm.YlOrRd)
cbar1 = plt.colorbar(map1, cax=cax1)

plt.show()

This gives:

enter image description here

This is probably more flexible but also requires more tweaking of padding and sizes on your part.