如何向子图添加轴?

Lui*_*uis 3 python matplotlib subplot

我有一系列相关的函数,我用 绘制matplotlib.pyplot.subplots,并且我需要在每个子图中包含相应函数的缩放部分。

我开始像这里解释的那样这样做,当只有一个图但没有子图时它可以完美地工作。

如果我用子图来做,我只会得到一个图,其中包含所有函数。这是我到目前为止得到的一个例子:

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(-10, 10, 0.01)
sinx = np.sin(x)
tanx = np.tan(x)

fig, ax = plt.subplots( 1, 2, sharey='row', figsize=(9, 3) )

for i, f in enumerate([sinx, cosx]):
    ax[i].plot( x, f, color='red' )
    ax[i].set_ylim([-2, 2])

    axx = plt.axes([.2, .6, .2, .2],)
    axx.plot( x, f, color='green' )
    axx.set_xlim([0, 5])
    axx.set_ylim([0.75, 1.25])

plt.show(fig)
Run Code Online (Sandbox Code Playgroud)

该段代码给出了下图:

在此输入图像描述

如何在每个子图中创建新的轴和绘图?

jrj*_*rjc 6

如果我理解得很好,你可以使用inset_axes

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


x = np.arange(-10, 10, 0.01)
sinx = np.sin(x)
tanx = np.tan(x)

fig, ax = plt.subplots( 1, 2, sharey='row', figsize=(9, 3) )

for i, f in enumerate([sinx, tanx]):
    ax[i].plot( x, f, color='red' )
    ax[i].set_ylim([-2, 2])

    # create an inset axe in the current axe:
    inset_ax = inset_axes(ax[i],
                          height="30%", # set height
                          width="30%", # and width
                          loc=10) # center, you can check the different codes in plt.legend?
    inset_ax.plot(x, f, color='green')
    inset_ax.set_xlim([0, 5])
    inset_ax.set_ylim([0.75, 1.25])
plt.show()
Run Code Online (Sandbox Code Playgroud)

插入轴