C2SM/pyvis

AxesGrid toolkit introduced ImageGrid

AnnikaLau opened this issue · 3 comments

Use ImageGrid directly in Bonus exercise of ex_2_3_colorbars.

ImageGrid uses the AxesDivider class (what is currently used in the exercise).
I assume this can be updated.

ImageGrid seems to be able to span more than one axes (contrary to what is written in the exercise)

The same is used in ex2_6_subplots (error in bonus exercise)

Ok, the difficult part is to define the axes.

This is the example in ex_2_3_colorbars

import cartopy.crs as ccrs
import matplotlib.pyplot as plt
import mplotutils as mpu
from mpl_toolkits.axes_grid1 import make_axes_locatable

# create sample data
lon, lat, data = mpu.sample_data_map(90, 48)
# ====

f, ax = plt.subplots(subplot_kw=dict(projection=ccrs.Orthographic(central_latitude=45)))
ax.coastlines()

h = ax.pcolormesh(lon, lat, data, transform=ccrs.PlateCarree())

# =======
# add colorbar

# create axes that has the right size
divider = make_axes_locatable(ax)
cbax = divider.append_axes("bottom", size="6.5%", pad=0.1, axes_class=plt.Axes)

# create colorbar in this axes
cbar = plt.colorbar(h, cax=cbax, orientation="horizontal", extend="both")

This creates the same figure using ImageGrid:

import functools

import cartopy
import cartopy.crs as ccrs
import matplotlib.pyplot as plt
import mplotutils as mpu
from mpl_toolkits.axes_grid1 import ImageGrid

lon, lat, data = mpu.sample_data_map(90, 48)

# EITHER a class, kwargs tuple
axes_class = (cartopy.mpl.geoaxes.GeoAxes, {"projection": ccrs.Orthographic(central_latitude=45)})

# OR using partial to bind the projection
axes_class=functools.partial(
        cartopy.mpl.geoaxes.GeoAxes, projection=ccrs.Orthographic(central_latitude=45)
)


fig = plt.figure()  # figsize=(4., 4.))
grid = ImageGrid(
    fig,
    111,  # similar to subplot(111)
    nrows_ncols=(1, 1),  # creates 1x1 grid of Axes
    cbar_mode="single",
    cbar_size="6.5%",
    cbar_pad=0.1,
    cbar_location="bottom",
    axes_class=axes_class,
)

ax = grid.axes_all[0]

ax.coastlines()
h = ax.pcolormesh(lon, lat, data, transform=ccrs.PlateCarree())


cbax = grid.cbar_axes[0]
cbax.colorbar(h, extend="both")

I had a quick look. When only adding a colorbar make_axes_locatable is simpler, but going for several subplots ImageGrid is worthwhile... Not sure yet if I actually want to remove it.