Horizontal colorbar over 2 of 3 subplots
Asked Answered
T

1

7

does someone know how to elegantly draw a horizontal colorbar over two of three subplots and one additional horizontal colorbar over the third subplot.

Ideally, the colorbars should have the same x-dimensions as the corresponding image axis. I did not find any nice solution, except setting up an entire image grid using matplotlib.gridspec.

Drawing single colorbars works perfectly fine with mpl_toolkits.axes_grid1.ImageGrid, but it fails when trying to draw a colorbar over two of three axes.

Toh answered 2/1, 2017 at 14:13 Comment(0)
S
15

The idea is to use fig.add_axes to add the axes where the colorbar will be. Here's an example:

import numpy as np
import matplotlib.pyplot as plt

matrix = np.random.random((10, 10, 3))

fig, ax = plt.subplots(1,3, figsize=(12, 3))
plt.subplots_adjust(left=0.05, right=0.85)
for i in range(3):
    im = ax[i].imshow(matrix[:, :, i], interpolation='nearest')
    ax[i].set_aspect("equal")

plt.draw()
p0 = ax[0].get_position().get_points().flatten()
p1 = ax[1].get_position().get_points().flatten()
p2 = ax[2].get_position().get_points().flatten()
ax_cbar = fig.add_axes([p0[0], 0, p1[2]-p0[0], 0.05])
plt.colorbar(im, cax=ax_cbar, orientation='horizontal')

ax_cbar1 = fig.add_axes([p2[0], 0, p2[2]-p2[0], 0.05])
plt.colorbar(im, cax=ax_cbar1, orientation='horizontal')

plt.show()

example_colorbar

Edit: The documentation of fig.add_axes say:

Add an axes at position rect [left, bottom, width, height] where all quantities are in fractions of figure width and height.

So to put the colorbar on top of the graphs you only need to change the bottom argumen to 1.

From

ax_cbar = fig.add_axes([p0[0], 0, p1[2]-p0[0], 0.05])
ax_cbar1 = fig.add_axes([p2[0], 0, p2[2]-p2[0], 0.05])

to

ax_cbar = fig.add_axes([p0[0], 1, p1[2]-p0[0], 0.05])
ax_cbar1 = fig.add_axes([p2[0], 1, p2[2]-p2[0], 0.05])

enter image description here

Sacroiliac answered 2/1, 2017 at 15:31 Comment(3)
that looks almost exactly how i want it. If now you tell me how to put the colorbar on top of the graphs, it would be perfect.Toh
@F.Win ok! I add a simple example.Sacroiliac
For some reason when I save the image, I get an empty (and transparent) image. MPL version: 3.5.0Excogitate

© 2022 - 2024 — McMap. All rights reserved.