簡體   English   中英

如何使用 matplotlib 將 inset_axes 添加到子圖

[英]How to add an inset_axes to a subplot with matplotlib

我正在嘗試 plot matplotlib 中的多個子圖,每個子圖都應該有一個插入軸。 我可以讓代碼示例適用於帶有使用mpl_toolkits.axes_grid.inset_locator.inset_axes()添加的插入軸的單個軸,並且我可以在沒有插入軸的情況下很好地 plot 子圖,但是當嘗試對 a 中的子圖執行相同操作時循環,我得到TypeError: 'AxesHostAxes' object is not callable on the second subplot 。 這似乎有點奇怪,當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
                            )

inset_axes 中的錯誤

對於未來的讀者: 這篇文章展示了在matplotlib中創建insets的方法。


這里問題的具體答案:這不是一個錯誤。 您正在重新定義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%") 

很好看的大笨蛋,這幫助我解決了類似的問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM