【问题标题】:How to set inset_axes position in matplotlib如何在 matplotlib 中设置 inset_axes 位置
【发布时间】:2017-01-02 02:47:47
【问题描述】:

我想在坐标轴内放置颜色条,因为科学出版物的空间有限。 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()

问候,

【问题讨论】:

    标签: python python-2.7 matplotlib


    【解决方案1】:

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

    这给出了以下图表:

    【讨论】:

    • 好的,谢谢,在这种情况下它适用于cbar = plt.colorbar(im,cax=cax,ax=ax),但我的轴实际上是单个图的子图。也许我应该在我的例子中包含它。相对于图形而不是相对于子轴调整颜色条位置并不方便。有什么技巧吗?像 "ax.get_position()" 或 ax.add_subaxes() ?
    猜你喜欢
    • 2018-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-19
    • 2014-06-02
    相关资源
    最近更新 更多