Lpng
Lpng

Reputation: 119

Adjust colorbar in a subplot

My goal is to plot three Graphs as subplots and use just one colorbar for the three of them, I have tryed that by making a figure with 4 subplots like shown in the following Code:

fig=plt.figure()
ax1=plt.subplot(1,4,1)
im=ax1.contourf(  M1, 50,vmax=100,vmin=-100)
x0,x1 = ax1.get_xlim()
y0,y1 = ax1.get_ylim()
ax1.set_aspect((x1-x0)/(y1-y0))
ax2=plt.subplot(1,4,2,aspect=1)
im2=ax2.contourf(  M2, 50,vmax=100,vmin=-100)
ax3=plt.subplot(1,4,3,aspect=1)
im3=ax3.contourf( M3, 50,vmax=100,vmin=-100)
cb = plt.subplot(1,4,4)
im4=plt.colorbar(im3)
#cb.ax.set_visible(True)
plt.show()

The Matrices M1, M2 and M3 are previously computed in the Code, but I guess for my Problem that is not very important. Also it is important that the three of the plots are squared-shaped. So far, I got: enter image description here

Upvotes: 0

Views: 754

Answers (1)

oekopez
oekopez

Reputation: 1090

A colorbar is either created in an already existing axes (aka subplot) element or it creates its own new one. To use the axes cb you can simply do:

im4 = plt.colorbar(im3, cax=cb)

to create the colorbar inside of cb.

But perhaps you want matplotlib to do this for you. Then you can specify from which axes (=subplots) colorbar should steal space:

fig=plt.figure()
ax1=plt.subplot(1,3,1)
im=ax1.contourf(  M1, 50,vmax=100,vmin=-100)
x0,x1 = ax1.get_xlim()
y0,y1 = ax1.get_ylim()
ax1.set_aspect((x1-x0)/(y1-y0))
ax2=plt.subplot(1,3,2,aspect=1)
im2=ax2.contourf(  M2, 50,vmax=100,vmin=-100)
ax3=plt.subplot(1,3,3,aspect=1)
im3=ax3.contourf( M3, 50,vmax=100,vmin=-100)
im4 = plt.colorbar(im3, ax=[ax1, ax2, ax3])

All this information is taken from help(plt.colorbar)

Upvotes: 2

Related Questions