如何使用matplotlib将inset_axes添加到子图

mjf*_*est 3 python matplotlib subplot

我正在尝试在matplotlib中绘制多个子图,每个子图应具有插入轴。我可以使用添加的插入轴使代码示例适用于单个轴mpl_toolkits.axes_grid.inset_locator.inset_axes(),并且可以在没有插入轴的情况下很好地绘制子图,但是当尝试在循环中对子图进行相同操作时,我进入TypeError: 'AxesHostAxes' object is not callable 了第二个子图。当number_of_plotsis == 1而不是> 1 时应该工作似乎有点奇怪。我应该怎么做,还是一个bug?(matplotlib.__version__是“ 1.5.1”)

from matplotlib import pyplot as plt
from mpl_toolkits.axes_grid.inset_locator import inset_axes
import numpy as np
x = np.linspace(0, 2 * np.pi, 100)
y = np.sin(x)
n_row, n_col = 4, 4
fig = plt.figure(1,(10,10))
#number_of_plots = 1 Works!
number_of_plots = n_row * n_col # Does not work!
for idx in range(number_of_plots):
    ax = fig.add_subplot(n_row, n_col, idx + 1)
    ax.plot(x, y)
    inset_axes = inset_axes(ax,
                            width="30%", # width = 30% of parent_bbox
                            height="30%", # height : 1 inch
                            )
Run Code Online (Sandbox Code Playgroud)

inset_axes中的错误

Imp*_*est 5

对于未来的读者:这篇文章展示了在matplotlib中创建插图的方法。


这里的问题的具体答案:这不是错误。您正在重新定义inset_axes

在行之前inset_axes = inset_axes(...)inset_axes是来自的函数mpl_toolkits.axes_grid.inset_locator。之后,inset_axes是该函数的返回值,即AxesHostAxes

当然,一般的建议是:切勿使用与导入或在代码中使用的函数相同的名称来调用变量。

具体解决方案:

ax_ins = inset_axes(ax, width="30%",  height="30%")
Run Code Online (Sandbox Code Playgroud)