gpt4 book ai didi

python - 如何在 matplotlib 中设置 inset_axes 位置

转载 作者:太空狗 更新时间:2023-10-30 01:37:14 35 4
gpt4 key购买 nike

我想将颜色条放在坐标轴内,因为科学出版物中空间有限。 inset_axes 似乎是创建子轴的不错选择,但我找不到一种简单的方法来放置除“loc = 0,1,2,3,4”之外的其他坐标:结果,颜色图标签位于图形之外。我想使用类似的工具,例如在 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()

enter image description here

问候,

最佳答案

一种不使用 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()

这给出了下图:

enter image description here

关于python - 如何在 matplotlib 中设置 inset_axes 位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39149188/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com