Horizontal colorbar over 2 of 3 subplots

╄→гoц情女王★ 提交于 2020-06-22 12:10:35

问题


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.


回答1:


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()

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])



来源:https://stackoverflow.com/questions/41428442/horizontal-colorbar-over-2-of-3-subplots

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!