Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid overlapping colorbar in xarray facet grid plot

Tags:

python

xarray

   import xarray as xr     
   import cartopy.crs as ccrs


    USA_PROJ = ccrs.AlbersEqualArea(central_longitude=-97., central_latitude=38.)
    g_simple = ds_by_month.t2m.plot(x='longitude',
                                    y='latitude',
                                    col='month',
                                    col_wrap=6,
                                    aspect=ds.dims['longitude'] / ds.dims['latitude'],
                                    subplot_kws=dict(projection=USA_PROJ),
                                    add_colorbar=False,
                                    transform=ccrs.PlateCarree())
    g_simple.add_colorbar(orientation='horizontal')
    for ax in g_simple.axes.ravel():
        ax.coastlines()
        ax.set_extent([-121, -72, 22.5, 50])

    plt.tight_layout()
    plt.show()

On running the code above, I get the foll. figure: enter image description here

How do I ensure that the colorbar is not overlapping the plots? the overlap happens even if I use the xarray default colorbar.

like image 965
user308827 Avatar asked Apr 03 '18 01:04

user308827


1 Answers

You could give the color bar its own set of axes and set the "bottom" value to negative so that it exceeds the bounding box, or otherwise set the subplots_adjust function using a keyword argument (i.e. hspace = 2 etc).

Here's an example with random data below (modified from matplotlib subplots example):

import numpy as np
import matplotlib.pyplot as plt

fig, axes = plt.subplots(nrows=2, ncols=6, figsize=(15,5))
for ax in axes.flat:
    im = ax.imshow(np.random.random((10,10)), vmin=0, vmax=1)

# color bar
fig.subplots_adjust(right=0.875) #also try using kwargs bottom, top, or hspace 
cbar_ax = fig.add_axes([0.1, -0.1, .8, .05]) #left, bottom, width, height
fig.colorbar(im, cax=cbar_ax, orientation="horizontal")

plt.show()

enter image description here

like image 118
Lauren Oldja Avatar answered Nov 03 '22 18:11

Lauren Oldja