Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Single colorbar for two subplots changes the size of one of the subplots

I am trying to add a single colorbar for two matshows using mainly the code at here and here.

My code is the following now, but the problem is that the colorbar moderates the size of the plot on the right. How can I prevent that?

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
# Generate some data that where each slice has a different range
# (The overall range is from 0 to 2)
data = np.random.random((2,10,10))
data *= np.array([1.5, 2.0])[:,None,None]

# Plot each slice as an independent subplot
fig, axes = plt.subplots(nrows=1, ncols=2)
for dat, ax in zip(data, axes.flat):
    # The vmin and vmax arguments specify the color limits
    im = ax.imshow(dat, vmin=0, vmax=2)

# Make an axis for the colorbar on the right side
divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="5%", pad=0.05)
fig.colorbar(im, cax=cax)
plt.tight_layout()
plt.show()

enter image description here

like image 315
Cupitor Avatar asked Apr 04 '15 14:04

Cupitor


People also ask

How does subplot change figure size?

To change figure size of more subplots you can use plt. subplots(2,2,figsize=(10,10)) when creating subplots.

How do I reduce the space between subplots?

We can use the plt. subplots_adjust() method to change the space between Matplotlib subplots. The parameters wspace and hspace specify the space reserved between Matplotlib subplots. They are the fractions of axis width and height, respectively.

How do I stop subplots from overlapping in Matplotlib?

Often you may use subplots to display multiple plots alongside each other in Matplotlib. Unfortunately, these subplots tend to overlap each other by default. The easiest way to resolve this issue is by using the Matplotlib tight_layout() function.


1 Answers

There are a couple approaches in the answers to Matplotlib 2 Subplots, 1 Colorbar. The last is simplest but doesn't work for me (the imshow plots are the same size, but both shorter than the colorbar). You could also run the colorbar under the images:

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
data = np.random.random((2,10,10))
data *= np.array([1.5, 2.0])[:,None,None]

fig, axes = plt.subplots(nrows=1, ncols=2)
for dat, ax in zip(data, axes.flat):
     im = ax.imshow(dat, vmin=0, vmax=2)

fig.colorbar(im,  ax=axes.ravel().tolist(), orientation='horizontal')
plt.show()

enter image description here

like image 135
cphlewis Avatar answered Oct 25 '22 19:10

cphlewis