【问题标题】:How to add axes to subplots?如何将轴添加到子图?
【发布时间】:2016-07-20 11:21:21
【问题描述】:

我有一系列用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)

这段代码给出了下图:

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

【问题讨论】:

  • @jeanrjc 我想要每个子图中的那些小盒子之一。在第一个中,我想要第一个函数(sinx)的一部分,在第二个中,第二个函数(tanx)的一部分。现在,小盒子按照大图放置,两个功能都在同一个盒子里。
  • 我终于弄明白了,所以我删除了评论并做出了回答。

标签: python matplotlib subplot


【解决方案1】:

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

【讨论】:

【解决方案2】:

直接从您已经创建的 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)

【讨论】:

    猜你喜欢
    • 2016-11-29
    • 2021-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-29
    • 1970-01-01
    • 2021-06-25
    • 2020-10-01
    相关资源
    最近更新 更多