Reduce horizontal colorbar padding

I'm trying to generate a plot with several axis, each one with their own colorbar (code below). If I use the default colorbar plotting I get too much horizontal spacing between the plot and the colorbar:

enter image description here

If I try to use the make_axes_locatable() method I get this horrible result:

enter image description here

What is going on and how can I fix this?


import numpy as np
from matplotlib import pyplot as plt
import matplotlib.gridspec as gridspec
from mpl_toolkits.axes_grid1 import make_axes_locatable

# Random data to plot
data = np.random.uniform(0., 1., (2, 100))
z = np.random.uniform(0., 10., 100)

# Define figure
fig = plt.figure(figsize=(30, 30))
gs = gridspec.GridSpec(12, 12)

for i in range(2):
    ax = plt.subplot(gs[2 * i:2 + (2 * i), 0:8])

    SC = plt.scatter(*data, c=z)

    # Colorbar 1
    cbar = plt.colorbar()

    # Colorbar 2
    # the_divider = make_axes_locatable(ax)
    # color_axis = the_divider.append_axes("right", size="1%", pad=0.)
    # cbar = plt.colorbar(SC, cax=color_axis)

    cbar.set_label("test", fontsize=15, labelpad=10)

fig.tight_layout()
plt.savefig('test.png', dpi=300, bbox_inches='tight')

1 answer

  • answered 2018-10-11 20:03 ImportanceOfBeingErnest

    Use the pad argument of colorbar to set the padding between the axes and the colorbar. pad is given in units of the fraction of the original axes' size to use as space. Here e.g. pad=0.01 might make sense.

    import numpy as np
    from matplotlib import pyplot as plt
    
    # Random data to plot
    data = np.random.uniform(0., 1., (2, 100))
    z = np.random.uniform(0., 10., 100)
    
    # Define figure
    fig, axes = plt.subplots(nrows=2, figsize=(30, 30))
    
    for i, ax in enumerate(axes.flat):
        sc = ax.scatter(*data, c=z)
        cbar = fig.colorbar(sc, ax=ax, pad=0.01)
        cbar.set_label("test", fontsize=15, labelpad=10)
    
    fig.tight_layout()
    plt.savefig('test.png', dpi=300, bbox_inches='tight')
    

    enter image description here