5

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')
Gabriel
  • 40,504
  • 73
  • 230
  • 404
  • 1
    the answer below was faster than me :) if you need it a reference is here also https://stackoverflow.com/questions/13310594/positioning-the-colorbar – oetoni Oct 11 '18 at 20:10

1 Answers1

8

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

ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712