Matplotlib offsetImage with bbox_inches tight pushing image up, creating white space in the bottom and not allowing me to properly align image layers

Viewed 134

I am trying to add an image as a layer on top of a figure to show a location of a few oceanographic weather buoys on a map.

It works for me up to a certain offset. When I go over a certain tuple number, my whole image gets dislocated and a large white space shows on the bottom. I am using bbox_inches=tight to save the figure the way I need.

import matplotlib.pyplot as plt
import matplotlib.image as mpimg
from matplotlib.offsetbox import  OffsetImage
from netCDF4 import Dataset as netcdf_dataset
import cartopy.crs as ccrs

varfigsizex=6
varfigsizey=7
fig = plt.figure(figsize=(varfigsizex, varfigsizey))

varllcrnrlon2=-121
varurcrnrlon2=-117
varllcrnrlat2=32.12
varurcrnrlat2=34.7

ax = plt.axes(projection=ccrs.PlateCarree())
ax.set_extent((varllcrnrlon2,varurcrnrlon2,varllcrnrlat2,varurcrnrlat2))
ax.coastlines()

buoy_img = mpimg.imread('buoy_img.png')
add_buoy = OffsetImage(buoy_img, zoom=0.4)
add_buoy.set_offset((230,720))
add_buoy.set_zorder(10)
ax.add_artist(add_buoy)

add_buoy_2 = OffsetImage(buoy_img, zoom=0.4)
add_buoy_2.set_offset((400,720))
add_buoy_2.set_zorder(10)
ax.add_artist(add_buoy_2)

add_buoy_3 = OffsetImage(buoy_img, zoom=0.4)
add_buoy_3.set_offset((650,590))
add_buoy_3.set_zorder(10)
ax.add_artist(add_buoy_3)

add_buoy_4 = OffsetImage(buoy_img, zoom=0.4)
add_buoy_4.set_offset((800,600))
add_buoy_4.set_zorder(10)
ax.add_artist(add_buoy_4)

name_file=''.join(['ca_buoy.png'])
fig.savefig(name_file, bbox_inches='tight', pad_inches=0, format='png', dpi=300)

It works up to a certain offset:

When I add additional layer images that I need, for example with set_offset((1200,100):

add_buoy_5 = OffsetImage(buoy_img, zoom=0.4)
add_buoy_5.set_offset((1200,100))
add_buoy_5.set_zorder(10)
ax.add_artist(add_buoy_5)

this is what happens:

it is displayed out of position, and dislocates the whole image:

I would like some help to understand why this happens, and how to properly fix my code.

0 Answers
Related