如何使用 matplotlib 将 inset_axes 添加到子图中
How to add an inset_axes to a subplot with matplotlib
我正在尝试在 matplotlib 中绘制多个子图,每个子图都应该有一个插入轴。我可以让代码示例适用于使用 mpl_toolkits.axes_grid.inset_locator.inset_axes()
添加的插入轴的单个轴,并且我可以在没有插入轴的情况下很好地绘制子图,但是当尝试对循环中的子图执行相同操作时,我得到TypeError: 'AxesHostAxes' object is not callable
在第二个子图中。这似乎有点奇怪,它应该在 number_of_plots
为 ==1 而不是 >1 时起作用。我应该怎么做,或者这是一个错误? (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
)
对于未来的读者:This post 展示了在 matplotlib 中创建插图的方法。
此处问题的具体答案:这不是错误。您正在重新定义 inset_axes
.
行 inset_axes = inset_axes(...)
之前,inset_axes
是 mpl_toolkits.axes_grid.inset_locator
的一个函数。之后,inset_axes
就是那个函数的return,也就是一个AxesHostAxes
。
一般建议当然是:永远不要调用与您在代码中导入或使用的函数同名的变量。
具体解决方案:
ax_ins = inset_axes(ax, width="30%", height="30%")
我正在尝试在 matplotlib 中绘制多个子图,每个子图都应该有一个插入轴。我可以让代码示例适用于使用 mpl_toolkits.axes_grid.inset_locator.inset_axes()
添加的插入轴的单个轴,并且我可以在没有插入轴的情况下很好地绘制子图,但是当尝试对循环中的子图执行相同操作时,我得到TypeError: 'AxesHostAxes' object is not callable
在第二个子图中。这似乎有点奇怪,它应该在 number_of_plots
为 ==1 而不是 >1 时起作用。我应该怎么做,或者这是一个错误? (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
)
对于未来的读者:This post 展示了在 matplotlib 中创建插图的方法。
此处问题的具体答案:这不是错误。您正在重新定义
inset_axes
.
行 inset_axes = inset_axes(...)
之前,inset_axes
是 mpl_toolkits.axes_grid.inset_locator
的一个函数。之后,inset_axes
就是那个函数的return,也就是一个AxesHostAxes
。
一般建议当然是:永远不要调用与您在代码中导入或使用的函数同名的变量。
具体解决方案:
ax_ins = inset_axes(ax, width="30%", height="30%")