Cupitor
Cupitor

Reputation: 11637

Colorbars close to subplots

How can I put colorbars beside each colormap that is in a subplot? A simplified version of my real code is here that shows my problem. As you can see all the colorbars are at the bottom right and also are making the last plot smaller.

from matplotlib import pyplot as plt
import numpy as np
def plots():
    fig,ax=plt.subplots(2,2)
    for i in range(2):    
        rho_mat,C_mat=np.random.uniform(size=(50,50)),np.random.uniform(size=(50,50))
        ax[0,i].set_title(r"$\rho_{X,Y}$")        
        p=ax[0,i].imshow(np.fliplr(rho_mat).T,extent=[0.,1,0.,1],vmin=0,vmax=1, interpolation='none')    
        ax[0,i].set_xlabel(r'$\epsilon_1$')
        ax[0,i].set_ylabel(r'$\epsilon_2$')
        fig.colorbar(p, shrink=0.5)
        ax[1,i].set_title(r"$C_{X,Y}$")
        p2=ax[1,i].imshow(np.fliplr(C_mat).T,extent=[0.,1,0.,1],vmin=0,vmax=1, interpolation='none')
        ax[1,i].set_xlabel(r'$\epsilon_1$')
        ax[1,i].set_ylabel(r'$\epsilon_2$')
        fig.colorbar(p2, shrink=0.5)
        plt.tight_layout()
    plt.show()
plots()

enter image description here

Upvotes: 0

Views: 108

Answers (1)

Molly
Molly

Reputation: 13610

The colorbar method has an optional keyword argument that allows you to specify the axes it is associated with.

In your code you could change the call to colorbar to something like this:

fig.colorbar(p, ax=ax[0,i], shrink=0.5)
fig.colorbar(p2, ax=ax[1,i],  shrink=0.5)

Upvotes: 1

Related Questions