如何向子图添加坐标轴?

3

我有一系列相关函数,使用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)

这段代码生成了以下图表:

enter image description here

我该如何在每个子图中创建新的坐标轴并绘制图形?


@jeanrjc 我想在每个子图中都有一个小框。在第一个子图中,我想要第一个函数(sinx)的一部分,在第二个子图中,我想要第二个函数(tanx)的一部分。现在,小框是根据大图放置的,并且两个函数都在同一个框中。 - Luis
最终我弄清楚了,所以我删除了评论并改为回答。 - jrjc
2个回答

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()

inset_axe


注意这个错误:https://dev59.com/I6Pia4cB1Zd3GeqPyW-b - Luis

3

直接从你已经创建的Axes实例中使用inset_axes:

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, tanx]):
    ax[i].plot( x, f, color='red' )
    ax[i].set_ylim([-2, 2])

    axx = ax[i].inset_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)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接