Search code examples
pythonmatplotlibcolorboxsubplot

Python - add colorbars in multiple plots for each plot


I have multiple plots on a figure. I would like to add colorbars for each results. These colorbars must have the same height of my results and i would like to limit the numbers displayed on the colorbar to 3 values (in order to have readable figures).enter image description here

My code is :

fig, axes = plt.subplots(nrows=1, ncols=3)

plt.tight_layout(pad=0.5, w_pad=2.5, h_pad=2.0)
ax1 = plt.subplot(131) # creates first axis
ax1.set_xticks([0,2000,500,1000,1500])
ax1.set_yticks([0,2000,500,1000,1500])
ax1.imshow(U,cmap='hot',extent=(X.min(),2000,Y.min(),2000))
ax1.set_title("$ \mathrm{Ux_{mes} \/ (pix)}$")
ax2 = plt.subplot(132) # creates second axis
ax2.set_xticks([0,2000,500,1000,1500])
ax2.set_yticks([0,2000,500,1000,1500])
ax2.imshow(UU,cmap='hot',extent=(X.min(),2000,Y.min(),2000))
ax2.set_title("$\mathrm{Ux_{cal} \/ (pix)}$")
ax3 = plt.subplot(133) # creates first axis
ax3.set_xticks([0,2000,500,1000,1500])
ax3.set_yticks([0,2000,500,1000,1500])
ax3.imshow(resU,cmap='hot',extent=(X.min(),2000,Y.min(),2000))
ax3.set_title("$\mathrm{\mid Ux - Ux \mid \/ (pix)}$ ")
plt.show()

I try to add : "fig.colorbar(U, axes=ax1,fraction=0.046, pad=0.04)" but it doesnt work...


Solution

  • Following the answer to @plonser,

    tick = np.linspace(min(your_variable),max(your_variable),3)
    
    plt.tight_layout(pad=0.5, w_pad=2.5, h_pad=2.0)
    ax1 = plt.subplot(131) # creates first axis
    ax1.set_xticks([0,2000,500,1000,1500])
    ax1.set_yticks([0,2000,500,1000,1500])
    i1 = ax1.imshow(U,cmap='hot',extent=(X.min(),2000,Y.min(),2000))
    plt.colorbar(i1,ax=ax1,ticks=tick)
    
    ax1.set_title("$ \mathrm{Ux_{mes} \/ (pix)}$")
    ax2 = plt.subplot(132) # creates second axis
    ax2.set_xticks([0,2000,500,1000,1500])
    ax2.set_yticks([0,2000,500,1000,1500])
    i2=ax2.imshow(UU,cmap='hot',extent=(X.min(),2000,Y.min(),2000))
    ax2.set_title("$\mathrm{Ux_{cal} \/ (pix)}$")
    plt.colorbar(i2,ax=ax2,ticks=tick)
    
    ax3 = plt.subplot(133) # creates first axis
    ax3.set_xticks([0,2000,500,1000,1500])
    ax3.set_yticks([0,2000,500,1000,1500])
    i3 = ax3.imshow(resU,cmap='hot',extent=(X.min(),2000,Y.min(),2000))
    ax3.set_title("$\mathrm{\mid Ux - Ux \mid \/ (pix)}$ ")
    plt.colorbar(i3,ax=ax3,ticks=tick)
    
    plt.show()
    

    When you specify, you do so using ax=ax1 and not axes=ax1. Also to limit the number of items in your colorbar, you can do so using the ticks option.