0

I am trying to add colorbar for each subplot. The 3D data is like (x,y,z). My codes are like:

fig,ax = plt.subplots(2,2,figsize=(15,15))
ax[0,0].scatter(x,y,s=z,c=z,cmap='jet')
ax[0,0].set_xlabel('XXX')
ax[0,0].set_ylabel('YYY')

So I am able to add x,y labels, add title for each subplot, but I just can't add the colorbar.

My codes for colorbar in a single plot are like: plt.colorbar(extend='both') or

colorbar = plt.colorbar(label='test',orientation='horizontal',shrink=0.8,pad=0.05,extend='both')

I saw the previous Q&A here matplotlib colorbar in each subplot, but sorry I don't understand how to apply to my case. Is there a way to add the colorbar, just like how I added the xlabel and title, please? Many thanks.

Jeremy
  • 849
  • 6
  • 15
  • You need `plt.colorbar(ax=ax[0,0], ....)` to add a colorbar to the top left subplot. Possibly you need to give it the result of `scat = ax[0,0].scatter(...`. – JohanC Feb 08 '20 at 12:54
  • Thanks, it worked, although I don't fully understand the underpinning reason. I used`cax1=ax[0,0].scatter(...)` and then `plt.colorbar(cax1,ax=ax[0,0],label='test',orientation='vertical',shrink=0.8,pad=0.05,extend='both')` – Jeremy Feb 08 '20 at 13:23
  • What you call `cax1`and I called `scat` is a ['pathcollection'](https://matplotlib.org/api/_as_gen/matplotlib.pyplot.scatter.html). It is some graphical object from which `colorbar` can extract the necessary information about colormaps and ranges. – JohanC Feb 08 '20 at 14:00

0 Answers0