The following code produces the image I want, but the colourbar is blank/white, and doesn't match the data:
def plot_array(da, ax=None, shift=True):
"""plots an array of lat by lon on a coastline map"""
m = basemap.Basemap()
m.drawcoastlines()
m.pcolormesh(da.lon, y=da.lat, data=da.T, latlon=True)
return m
# 'monthly mean' is an xarray DataArray
fig = plt.figure(0, (14, 8))
grid = ImageGrid(fig, 111, nrows_ncols=(3, 4), axes_pad=0.3,
cbar_mode='single', cbar_location="bottom",)
for i, m in enumerate(months):
plt.sca(grid[i])
plot_array(monthly_mean.sel(month=i + 1))
plt.title(m)
plt.suptitle("{b} - {y} monthly means".format(b=benchmark, y=year))
# plt.colorbar()
plt.tight_layout()
os.makedirs("plots/monthly_means/{y}".format(y=year), exist_ok=True)
plt.savefig("plots/monthly_means/{y}/{b}_{y}.png".format(b=benchmark, y=year))
plt.close()
Is there something else I need to do to get the colorbar working with ImageGrid, or do ImageGrid and Basemap just not play well together?
As far as I understand, it's not a Basemap problem. The ImageGrid()
call just sets up a blank set of axes for the colorbar that can be passed to plt.colorbar()
via the cax
argument. By default ImageGrid()
has the argument cbar_set_cax=True
, which sets the cax
attribute on each of the subplots. You can then pass this to colorbar()
:
...
plt.colorbar(cax=grid[0].cax)
plt.tight_layout()
...
That will just use the currently active axes to determine the colorbar data range, so it'll only be consistent with the final plot. You're going to have to use combinations of vmin/vmax
with pcolormesh()
to ensure consistency across all the plots.
Matplotlib can not define what you want to plot on a colorbar. Write like
...
pcm = m.pcolormesh(da.lon, y=da.lat, data=da.T, latlon=True)
plt.colorbar(pcm)
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With