简体   繁体   English

如何在matplotlib中设置inset_axes位置

[英]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. inset_axes似乎是创建子轴的一个不错的选择,但是我找不到除'loc = 0,1,2,3,4'以外的其他坐标的简单放置方法:结果,颜色映射表标签位于图的外部。 I would like to use similar tool as the (x,y) coordinates find in ax.annotate() for example, that allow comprehensive positioning. 我想使用与ax.annotate()中的(x,y)坐标类似的工具,以实现全面定位。

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. 不使用的一种可能的解决方案inset_axes是简单地使用matplotlib的colorbar ,但允许它出现在图中。

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: 这给出了下图:

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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