I am trying to add a single colorbar
for two matshow
s 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()
To change figure size of more subplots you can use plt. subplots(2,2,figsize=(10,10)) when creating 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.
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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With