如何在颜色条和图像之间设置一些 space

How to set some space between the colorbar and the image

我想在图像和颜色条之间设置一些 space,我试过 pad 但什么也没做,所以... 这是我的形象:

这是代码:

from mpl_toolkits.axes_grid1 import make_axes_locatable
from matplotlib.colors import LogNorm
from matplotlib.ticker import LogLocator
from matplotlib import rcParams
rcParams['font.size']=35
x = np.arange(0,16,1)
yx= np.linspace(-50,0,38)
mx = np.random.rand(15,38)
m2 = np.linspace(0,6,38)
fig, ax = plt.subplots(figsize=(40,30))
divider = make_axes_locatable(ax)


cax = divider.append_axes('right', size='5%', pad=2)

im = ax.pcolor(x,yx,mx.T,norm=LogNorm(0.1, 100),cmap= 'jet')
cbar = fig.colorbar(im,pad = 2,cax=cax, orientation='vertical')
cbar.ax.yaxis.set_major_locator(LogLocator())  # <- Why? See above.
cbar.ax.set_ylabel('Resistividade \u03C1 [ohm.m]', rotation=270)
ax2=ax.twiny()
ax2.plot(m2,yx,'k--',linewidth=10)
#ax2.set_xlim([0,60])
ax2.set_xlabel('Resistividade \u03C1 [ohm.m]')
ax.set_xlabel('Aquisição')
ax.set_ylabel('Profundidade [m]')
#fig.tight_layout()
plt.savefig('mrec_1'+'.png',bbox_inches = "tight", format='png', dpi=300)  
plt.show()

辅助轴占据了图中用于轴的所有 space。因此,无论你给 ax 的颜色条填充什么,它都不会影响 ax2.

一个 hacky-ish 的解决方案是也将你的辅助轴与主轴完全相同,然后删除第二个颜色条所在的轴:

fig, ax = plt.subplots(figsize=(10, 8))

pad = 0.2  # change the padding. Will affect both axes

im = ax.pcolor(x, yx, mx.T, norm=LogNorm(0.1, 100), cmap='jet')
divider = make_axes_locatable(ax)
cax = divider.append_axes('right', size='5%', pad=pad)

ax2 = ax.twiny()

ax2.plot(m2, yx, 'k--', linewidth=10)
ax2.set_xlim([0, 60])
ax2.set_xlabel('Resistividade \u03C1 [ohm.m]')
ax.set_xlabel('Aquisição')
ax.set_ylabel('Profundidade [m]')

cbar = fig.colorbar(im,pad = 2,cax=cax, orientation='vertical')
cbar.ax.yaxis.set_major_locator(LogLocator())
cbar.ax.set_ylabel('Resistividade \u03C1 [ohm.m]', rotation=270)

secondary_divider = make_axes_locatable(ax2)  # divide second axes
redundant_cax = secondary_divider.append_axes('right', size='5%', pad=pad)
redundant_cax.remove()  # delete the second (empty) colorbar

plt.show()