如何向子批次添加轴?

2024-09-28 23:27:59 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我开始像解释的那样做here,当有一个单独的图时,它可以完美地工作,但是没有子图。在

如果我用子图来做,我只得到一个图,里面有所有的函数。以下是我目前所取得的成果的一个例子:

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)

这段代码给出了以下图表:

enter image description here

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


Tags: 函数importplotmatplotlibasnpfigplt
1条回答
网友
1楼 · 发布于 2024-09-28 23:27:59

如果我理解得很好,你可以使用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()

inset_axe

相关问题 更多 >