简体   繁体   中英

How to correct subplot image size with colorbars in matplotlib python?

I want to make a 3x2 subplot image in python. With the images in third row I have added a colorbar. But it the image size gets small as compared to the top rows. Is there anyway to fix the image size the same as of top two rows while having a colorbar in the third row?

Here's my python code

#Imports
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import matplotlib.image as image
import matplotlib.colors
from matplotlib.colors import ListedColormap
#data

bird = image.imread('Desktop/bird.jpeg')   

fig, (ax1, ax2, ax3) = plt.subplots(3,2,figsize=(5,5)) 
ax1[0].imshow(bird)
ax1[0].set_ylabel('Row 1', size=8)
ax1[0].set_yticks([]) #display no ticks 
ax1[0].set_xticks([])   

ax1[1].imshow(bird)
ax1[1].set_yticks([]) 
ax1[1].set_xticks([])   

ax2[0].imshow(bird)
ax2[0].set_yticks([]) 
ax2[0].set_xticks([])
ax2[0].set_ylabel('Row 2', size=8)

ax2[1].imshow(bird)
ax2[1].set_yticks([]) 
ax2[1].set_xticks([])  

#Generating Color Map
cmap = matplotlib.colors.LinearSegmentedColormap.from_list("", ["Red","Green","Blue"])

# Right Image
bird_3 = ax3[1].imshow(bird, cmap = cmap)
ax3[1].set_yticks([]) 
ax3[1].set_xticks([])
cbar_int = fig.colorbar(bird_3,orientation='horizontal', ax=ax3[1]) 
cbar_int.set_label('CBar', size=8, rotation=0)
cbar_int.ax.tick_params(labelsize=8) 
bird_3.set_clim(vmin=-1, vmax=1) 

# Left Image
bird_4 = ax3[0].imshow(bird, cmap = cmap)
ax3[0].set_yticks([]) 
ax3[0].set_xticks([])
ax3[0].set_ylabel('Row 3', size=8)
cbar_int = fig.colorbar(bird_4,orientation='horizontal', ax=ax3[0]) 
cbar_int.set_label('CBar', size=8, rotation=0)
cbar_int.ax.tick_params(labelsize=8) 
bird_3.set_clim(vmin=-1, vmax=1)    

plt.show()

The following results I get with it. You see row 3 images are small compared to row 1 and 2.

在此处输入图像描述

Matplotlib steals space from the host axes. However, you can specify more than one axes to steal space from. So above you can easily do:

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

fig, axs = plt.subplots(3, 2)
for ax in axs.flat:
    pc = ax.imshow(np.random.randn(20,40))

fig.colorbar(pc, ax=axs[:, 1], orientation='horizontal')
fig.colorbar(pc, ax=axs[:, 0], orientation='horizontal')
plt.show()

and space is stolen from all three axes in each column.

You can also specify constrained_layout=True for slightly better layout.

Note that with imshow the axes have a fixed aspect ratio, so there is always going to be issues with white space.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM