为了账号安全,请及时绑定邮箱和手机立即绑定

在matplotlib的子图中嵌入小图

在matplotlib的子图中嵌入小图

DIEA 2019-10-28 14:30:59
如果要在较大的图中插入一个较小的图,则可以使用Axes,例如此处。问题是我不知道如何在子图中执行相同的操作。我有几个子图,我想在每个子图中绘制一个小图。示例代码将如下所示:import numpy as npimport matplotlib.pyplot as pltfig = plt.figure()for i in range(4):    ax = fig.add_subplot(2,2,i)    ax.plot(np.arange(11),np.arange(11),'b')    #b = ax.axes([0.7,0.7,0.2,0.2])     #it gives an error, AxesSubplot is not callable    #b = plt.axes([0.7,0.7,0.2,0.2])    #plt.plot(np.arange(3),np.arange(3)+11,'g')    #it plots the small plot in the selected position of the whole figure, not inside the subplot有任何想法吗?提前致谢!
查看完整描述

3 回答

?
宝慕林4294392

TA贡献2021条经验 获得超8个赞

我写了一个非常类似于plt.axes的函数。您可以使用它来绘制子子图。有一个例子...


import matplotlib.pyplot as plt

import numpy as np


def add_subplot_axes(ax,rect,axisbg='w'):

    fig = plt.gcf()

    box = ax.get_position()

    width = box.width

    height = box.height

    inax_position  = ax.transAxes.transform(rect[0:2])

    transFigure = fig.transFigure.inverted()

    infig_position = transFigure.transform(inax_position)    

    x = infig_position[0]

    y = infig_position[1]

    width *= rect[2]

    height *= rect[3]  # <= Typo was here

    subax = fig.add_axes([x,y,width,height],axisbg=axisbg)

    x_labelsize = subax.get_xticklabels()[0].get_size()

    y_labelsize = subax.get_yticklabels()[0].get_size()

    x_labelsize *= rect[2]**0.5

    y_labelsize *= rect[3]**0.5

    subax.xaxis.set_tick_params(labelsize=x_labelsize)

    subax.yaxis.set_tick_params(labelsize=y_labelsize)

    return subax


def example1():

    fig = plt.figure(figsize=(10,10))

    ax = fig.add_subplot(111)

    rect = [0.2,0.2,0.7,0.7]

    ax1 = add_subplot_axes(ax,rect)

    ax2 = add_subplot_axes(ax1,rect)

    ax3 = add_subplot_axes(ax2,rect)

    plt.show()


def example2():

    fig = plt.figure(figsize=(10,10))

    axes = []

    subpos = [0.2,0.6,0.3,0.3]

    x = np.linspace(-np.pi,np.pi)

    for i in range(4):

        axes.append(fig.add_subplot(2,2,i))

    for axis in axes:

        axis.set_xlim(-np.pi,np.pi)

        axis.set_ylim(-1,3)

        axis.plot(x,np.sin(x))

        subax1 = add_subplot_axes(axis,subpos)

        subax2 = add_subplot_axes(subax1,subpos)

        subax1.plot(x,np.sin(x))

        subax2.plot(x,np.sin(x))

if __name__ == '__main__':

    example2()

    plt.show()



查看完整回答
反对 回复 2019-10-28
?
牛魔王的故事

TA贡献1830条经验 获得超3个赞

您现在可以使用matplotlibs inset_axes方法执行此操作(请参阅docs):


from mpl_toolkits.axes_grid.inset_locator import inset_axes

inset_axes = inset_axes(parent_axes,

                    width="30%", # width = 30% of parent_bbox

                    height=1., # height : 1 inch

                    loc=3)

更新:正如Kuti所指出的,对于matplotlib 2.1版或更高版本,您应该将import语句更改为:


from mpl_toolkits.axes_grid1.inset_locator import inset_axes

现在,还有一个完整的示例显示了所有可用的选项。


查看完整回答
反对 回复 2019-10-28
  • 3 回答
  • 0 关注
  • 1859 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信