簡體   English   中英

如何存儲一個function的output

[英]How to store the output of a function

我有一個 dataframe 如下: x = [1,2,3.....10000] y = [1,2,3.....10000]

我在 matplotlib 中使用 SpanSelector 工具對 x 數據進行選擇。 根據選擇,我得到兩個值 (xmin, xmax)

現在我想要 plot 另一個 plot(與我已經繪制的不同),x 軸設置為 (xmin, xmax)

`

ax.errorbar(x=x,y=y,yerr=y_err)

def onselect(xmin, xmax):

    print('\nLower value: ',xmin)
    print('Upper value: ',xmax)
    return xmin,xmax

span = SpanSelector(
    ax,
    onselect,
    "horizontal",
    useblit=True,
    props=dict(alpha=0.5, facecolor="tab:green"),
    interactive=True,
    drag_from_anywhere=True
)

`

我嘗試在函數內部使用 plt 命令,它打印給定的打印語句,但不打印。

我基本上想要這個: https://matplotlib.org/stable/gallery/widgets/span_selector.html用於我自己的用例,我無法做到。 執行相同操作的任何其他方法也足夠了。

問題是您傳遞給 SpanSelector 的SpanSelector是作為回調實現的,其中不使用返回值。 因此,您必須為這個 function 找到一種方法,將值永久存儲在某個地方(超出函數的生命周期/ scope)而不返回它。 實際上有兩種方法:要么,您使用全局變量並讓 function 寫入它們。 這看起來像這樣:

xmin_global = None
xmax_global = None

def onselect(xmin, xmax):
    global xmin_global 
    global xmax_global 
    xmin_global = xmin
    xmax_global = xmax

然而,通常不鼓勵使用全局變量,因為很難跟蹤行為,而且代碼庫越大,理解代碼的作用和調試它就變得非常復雜。 然而,對於小型獨立代碼片段,通常可以使用它。

另一種(在我看來更好)的方法是將onselect定義為 object 的一種方法,它將變量xminxmax作為成員屬性。 然后該方法可以將 object 的這些屬性設置為您的值,然后您可以從 object 檢索它們。這可能看起來像這樣:

class Selector:
    
    def __init__(self, ax):
        self.ax = ax
        self.xmin = None
        self.xmax = None
        
        self.span = SpanSelector(
            self.ax,
            self.onselect,
            "horizontal",
            useblit=True,
            props=dict(alpha=0.5, facecolor="tab:blue"),
            interactive=True,
            drag_from_anywhere=True
        )
        
    def onselect(self, xmin, xmax):
        self.xmin = xmin
        self.xmax = xmax
        
selector = Selector(ax1)

在這里,我也在__init__方法中的 class 內部初始化了SpanSelector 但這也可以在 class 之外完成。要點是onselect作為一種方法可以訪問 object 的所有屬性,並且可以通過self引用寫入它們。 可以將它們視為 class 的 scope 中的全局變量。稍后您可以使用selector.xminselector.xmax訪問它們。

暫無
暫無

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

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