简体   繁体   中英

How to set inset_axes position in matplotlib

I would like to place colorbar inside axes, because room is scarce in scientific publication. inset_axes seems like a good choice to creat sub axes, but I cannot find an easy way to place with other coordinate than 'loc = 0,1,2,3,4' : Results, the colormap label lay outside of the figures. I would like to use similar tool as the (x,y) coordinates find in ax.annotate() for example, that allow comprehensive positioning.

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid.inset_locator import inset_axes

plt.close('all')

##### build some fake data to map ##########
x = np.linspace(-0.7,0.7,num = 50)
y = np.linspace(0,1,num = 100)
ext = (x[0],x[-1],y[-1],y[0])
xx,yy = np.meshgrid(x,y,indexing = 'ij')
U = np.cos(xx**2 + yy**2)

#### build figures and axes ###########
fig, ax = plt.subplots(1,1)
fig.set_size_inches(4, 3)
#### plot ############
im = ax.imshow(U,interpolation = 'nearest', extent = ext, aspect = 'equal',vmin=0,vmax=np.amax(U))

#### insert colorbar ######

cax = inset_axes(ax,width = '5%',height = '17%',loc = 1) 
cbar = plt.colorbar(im, ax = ax,cax = cax ,format = '%.1f' ,ticks = [0,np.amax(U)])

cax = inset_axes(ax,width = '5%',height = '17%',loc = 3)
cbar = plt.colorbar(im, ax = ax,cax = cax,format = '%.1f' ,ticks = [0,np.amax(U)])

### stuff ####

fig.tight_layout()
plt.show()

在此处输入图片说明

Regards,

One possible solution which does not use inset_axes is to simply use matplotlib's colorbar but allow it to appear inside the figure.

x = np.linspace(-0.7,0.7,num = 50)
y = np.linspace(0,1,num = 100)
ext = (x[0],x[-1],y[-1],y[0])
xx,yy = np.meshgrid(x,y,indexing = 'ij')
U = np.cos(xx**2 + yy**2)

#### build figures and axes ###########
fig1, ax = plt.subplots(1,1)
fig1.set_size_inches(4, 3)
#### plot ############
plt.imshow(U,interpolation = 'nearest', extent = ext, aspect = 'equal',vmin=0,vmax=np.amax(U))

#### insert colorbar ######

cax = fig1.add_axes([0.12, 0.52, 0.86, 0.3]) #change the position and size of the colorbar here
cax.get_xaxis().set_visible(False)
cax.get_yaxis().set_visible(False)
cax.set_frame_on(False)
cbar = plt.colorbar()
cbar.set_ticks([0,np.max(U)]) #set the colorbar ticks

### stuff ####

plt.show()

This gives the following graph:

在此处输入图片说明

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