Prevent color bar and title from affecting size of the plot in Matplotlib

Viewed 899
def plot_rain(num, show=False):
    i = 0 
    for x in range(num):
        ifile = "{:02d}".format(x)
        saveimg_name = 'noaa_images/rain/rain.f0{}.png'.format(ifile)

        data, _, lats, lons, datetime = collect_data(ifile, RAIN)
        lons = np.apply_along_axis(lambda row: row - 360, 1, lons)
        # 0.0001, 0.003,0.0005   make no blue background not sure why
        cint = np.arange(0.0001, 0.003,0.0005)

        fig, ax = plt.subplots()

        # Create new figure
        mapcrs = ccrs.Mercator(central_longitude=263, min_latitude=23, max_latitude=50, globe=None)

        # Set data projection
        datacrs = ccrs.PlateCarree()

        gs = gridspec.GridSpec(2, 1, height_ratios=[1, .02], bottom=.07, 
            top=.99, hspace=0.01, wspace=0.01) 
        # Add the map and set the extent
        ax = plt.subplot(gs[0], projection=mapcrs, frameon=False)
        ax.set_extent([293, 233 , 23, 55], ccrs.PlateCarree())
        ax.set_frame_on(False)
        # Add state/country boundaries to plot
        ax.add_feature(cfeature.STATES)
        ax.add_feature(cfeature.BORDERS)


        #Choose colormap  https://matplotlib.org/2.0.1/users/colormaps.html   
        cf = ax.contourf(lons, lats, data, cint, cmap=plt.cm.jet,transform=datacrs, alpha=0.7)

        # add color bar and title
        # fig.text(.2, .12, "Kg of rainfall per m^2 s",fontweight="bold")
        # cb = fig.colorbar(cf, pad=0, aspect=50, orientation='horizontal')   

        ax.axis('off')
        i = i + 1
        if show:
            plt.show()
        else:
            plt.savefig(saveimg_name, transparent=True, bbox_inches='tight', pad_inches=0,quality =100,progressive= True)

This above code will generate an image and then I use folium to overlay the image on a map.

Image1 is what it looks like without adding title and color bar. img1

Here is what it looks like with title and color bar I use this code

fig.text(.2, .12, "Kg of rainfall per m^2 s",fontweight="bold")
cb = fig.colorbar(cf, pad=0, aspect=50, orientation='horizontal')  

Img2

After I added title and color bar, the original plots are shrunk. What I want is to add color bar and title without affecting the size of the plot. Thanks for the help!

1 Answers

To avoid resizing of existing axes when adding a colorbar you can give the colorbar its own axes via the cax keyword argument. Here is a minimal example as I cannot reproduce your plot without more data.

fig, ax = plt.subplots()
c = ax.imshow(np.random.random((10, 10)))
cbar_ax = fig.add_axes([0.1, 0.1, 0.05, 0.8])
# new ax with dimensions of the colorbar

cbar = fig.colorbar(c, cax=cbar_ax)
plt.show()
Related