@[Toc]# 1、问题描述
- python在绘图过程中,可能会出现colorbar高度与主图不匹配情况,需要进行调整,使得与主图高度对齐,使图像更美观。
- 示例:colorbar位置高于主图
2、解决方法
- 通过调整shrink参数匹配对齐,pad调整x轴方向与主图位置
...
map = ax.pcolormesh(X, Y, data * mask, cmap=cmaps, vmin=CC1, vmax=CC2)
cbar = plt.colorbar(mpl.cm.ScalarMappable(norm=norm, cmap=cmaps),shrink=0.97,pad=0.02)
...
- 获取主图位置进行匹配对齐
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
x = np.arange(20)
y = np.arange(20)
[X,Y]= np.meshgrid(x,y)
Z = X**2 + Yfig=plt.figure(figsize=(12,6))
ax = plt.axes()
norm =mpl.colors.Normalize(vmin=0, vmax=100)
map = ax.pcolormesh(X, Y, Z,cmap='jet', norm=norm)
# 获取主图的位置进行匹配
ax1=fig.add_axes([ax.get_position().x1+0.01,ax.get_position().y0,0.02,ax.get_position().height])
i = fig.colorbar(mpl.cm.ScalarMappable(norm=norm,cmap='jet'),ax = map,cax=ax1,orientation='vertical')
i.ax.tick_params(labelsize=15,width=0.5,length=0.5)
i.set_ticks(range(0,100,10))
i.outline.set_linewidth(0.3)
- 使用 inset_axes 创建一个 ax 内小窗体,并作为colorbar
...
from mpl_toolkits.axes_grid1.inset_locator import inset_axes
map = ax.pcolormesh(X, Y, data * mask, cmap=cmaps, vmin=CC1, vmax=CC2)
cb_ax = inset_axes(ax, width="3%", height="100%", loc='lower left', bbox_to_anchor=(1.01, 0., 1, 1),bbox_transform=ax.transAxes, borderpad=0)
cbar = plt.colorbar(mpl.cm.ScalarMappable(norm=norm, cmap=cmaps),ax=map,cax=cb_ax)
...