Python – matplotlib colorbar placement and size

layoutmatplotlibpython

I'm using quadmesh to create a simple polar projection plot. Here's a minimal script which produces basically what I'm trying to do:

from __future__ import unicode_literals
import numpy as np
import matplotlib.pyplot as plt

def make_plot(data,fig,subplot):
    nphi,nt = data.shape
    phi_coords = np.linspace(0,np.pi*2,nphi+1) - np.pi/2.
    theta_coords = np.linspace(0,np.radians(35),nt+1)

    ax = fig.add_subplot(subplot,projection='polar')
    ax.set_thetagrids((45,90,135,180,225,270,315,360),(9,12,15,18,21,24,3,6))
    ax.set_rgrids(np.arange(10,35,10),fmt='%s\u00b0')  

    theta,phi = np.meshgrid(phi_coords,theta_coords)
    quadmesh = ax.pcolormesh(theta,phi,data)
    ax.grid(True)
    fig.colorbar(quadmesh,ax=ax)
    return fig,ax


a = np.zeros((360,71)) + np.arange(360)[:,None]
b = np.random.random((360,71))
fig = plt.figure()
t1 = make_plot(a,fig,121)
t2 = make_plot(b,fig,122)
fig.savefig('test.png')

The above script creates a plot which looks like this:

enter image description here

I would like the colorbars to:

  1. Not overlap the 6 label.
  2. be scaled such that they are approximately the same height as the plot.

Is there any trick to make this work properly? (Note that this layout isn't the only one I will be using — e.g. I might use a 1×2 layout, or a 4×4 layout … It seems like there should be some way to scale the colorbar to the same height as the associated plot…)

Best Answer

This combination (and values near to these) seems to "magically" work for me to keep the colorbar scaled to the plot, no matter what size the display.

plt.colorbar(im,fraction=0.046, pad=0.04)