1

I'm trying to add a color bar to my plot, which contains 4 subplots. I've added the subplots manually using this code:

extent = [-8, 37, 28, 46]
fig = plt.figure(figsize=(5.5, 3.5), constrained_layout= False)
spec = fig.add_gridspec(ncols=2, nrows=2)
ax0 = fig.add_subplot(spec[0, 0], projection=ccrs.PlateCarree(), frameon= False)
ax0.set_extent(extent)

ax1 = fig.add_subplot(spec[0, 0], projection=ccrs.PlateCarree(), frameon= False)
ax1.set_extent(extent)

I wrote these lines up to ax3. Now that I try to make a color bar, using plt.color bar()

It adds a color bar only to the last subplot... I've tried other online solutions, but they all use the fig, axes= plt.subplots(...) which I don't use..

edit- this question How to have one colorbar for all subplots doesn't really help me... when I try to run this code

fig.subplots_adjust(right=0.8)

cbar_ax = fig.add_axes([0.85, 0.15, 0.05, 0.7])

fig.colorbar(ax3, cax=cbar_ax)

I get this error- AttributeError: 'GeoAxesSubplot' object has no attribute 'get_array' I'm using Cartopy to make a hist2d of global occurrences.

Does anyone have an idea how to overcome this? Thanks in advance, Karin.

KarinP
  • 101
  • 1
  • 7
  • I find this answer to be very helpful. [https://stackoverflow.com/questions/13784201/how-to-have-one-colorbar-for-all-subplots](https://stackoverflow.com/questions/13784201/how-to-have-one-colorbar-for-all-subplots) – r-beginners Jan 06 '22 at 12:52
  • 1
    Does this answer your question? [How to have one colorbar for all subplots](https://stackoverflow.com/questions/13784201/how-to-have-one-colorbar-for-all-subplots) – Jody Klymak Jan 06 '22 at 13:24
  • when I run this in my code - fig.subplots_adjust(right=0.8) cbar_ax = fig.add_axes([0.85, 0.15, 0.05, 0.7]) fig.colorbar(ax3, cax=cbar_ax) it gives me this error- AttributeError: 'GeoAxesSubplot' object has no attribute 'get_array' I guess it's important to say I'm using cartopy? – KarinP Jan 06 '22 at 14:02
  • Sorry! I'm new here... added it in my question – KarinP Jan 06 '22 at 14:11
  • Colorbar does not take an axes as an argument. We can't help you without a complete example, but the argument to colorbar is usually a ScalarMappable, which will be returned to you by whatever you are colormapping. Please read https://matplotlib.org/stable/gallery/subplots_axes_and_figures/colorbar_placement.html – Jody Klymak Jan 06 '22 at 15:26
  • I don't think I understand what other information is needed... – KarinP Jan 06 '22 at 15:53
  • I use a lot of dataframes so it's quite difficult to add them or their code here. I just need help understanding how when you create subplots manually (without axes) can you create a united color bar – KarinP Jan 06 '22 at 15:55

1 Answers1

0

I managed to solve the problem... just used fig, axes =plt.subplots(...) and converted my code to use this code :-)

KarinP
  • 101
  • 1
  • 7