Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Empty colorbar using basemap.pcolor in an ImageGrid

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()

blank colorbar

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?

like image 317
naught101 Avatar asked Jun 20 '16 07:06

naught101


2 Answers

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.

like image 67
Deditos Avatar answered Nov 06 '22 09:11

Deditos


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)
...
like image 3
Serenity Avatar answered Nov 06 '22 10:11

Serenity