简体   繁体   中英

Matplotlib: how to get color bars that are one on top of each other as opposed to side by side?

I have the following code:

import matplotlib.pyplot as plt
import numpy as np

img1 = np.zeros([512,512])
img2 = np.zeros([512,512])

plt.figure(figsize=(10,10))
plt.imshow(img1, cmap='inferno')
plt.axis('off')
cba = plt.colorbar(shrink=0.25)
cba.ax.set_ylabel('Events / counts', fontsize=14)
cba.ax.tick_params(labelsize=12)
plt.imshow(img2, cmap='turbo', alpha=0.5)
plt.axis('off')
cba = plt.colorbar(shrink=0.25)
cba.ax.set_ylabel('Lifetime / ns)', fontsize=14)
cba.ax.tick_params(labelsize=12)
plt.tight_layout()
plt.show()

which produces the following output:

在此处输入图像描述

My question is, how can I get color bars that are on top of one another as opposed to next to each other? Ideally, I would like to get something like this:

在此处输入图像描述

You can grab the position of the ax and use it to create new axes for the colorbars. Here is an example:

import numpy as np
import matplotlib.pyplot as plt
from scipy import ndimage

data = ndimage.gaussian_filter(np.random.randn(512, 512), sigma=15, mode='nearest') * 20

fig, ax = plt.subplots()
im1 = ax.imshow(data, vmin=-1, vmax=0, cmap='viridis')
data[data < 0] = np.nan
im2 = ax.imshow(data, vmin=0.001, vmax=1, cmap='Reds_r')
ax.axis('off')

pos = ax.get_position()
bar_h = (pos.y1 - pos.y0) * 0.5  # 0.5 joins the two bars, e.g. 0.48 separates them a bit
ax_cbar1 = fig.add_axes([pos.x1 + 0.02, pos.y0, 0.03, bar_h])
cbar1 = fig.colorbar(im1, cax=ax_cbar1, orientation='vertical')
ax_cbar2 = fig.add_axes([pos.x1 + 0.02, pos.y1 - bar_h, 0.03, bar_h])
cbar2 = fig.colorbar(im2, cax=ax_cbar2, orientation='vertical')
plt.show()

示例图

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM