亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

matplotlib.pyplot.plot 的包裝函數

matplotlib.pyplot.plot 的包裝函數

胡說叔叔 2023-01-04 14:29:45
我是 Python 的新手(但我對許多其他語言都很有經驗?。┎⑶艺诰帉懸粋€ Python 腳本來處理科學測量數據。我最終得到了許多類函數,每個類函數都調用 matplotlib.pyplot.plot()。我在下面包括一個簡單的例子:def plot_measurement(self, x, x_label, y, y_label, plot_label = "", format = "-b", line_width = 1, latex_mode = False):    if (plot_label == ""):        plot_label = self.identifier    if (latex_mode):        matplotlib.rc("text", usetex = True)        matplotlib.rc("font", family = "serif")    matplotlib.pyplot.plot(x, y, format, linewidth = line_width, label = plot_label)    matplotlib.pyplot.xlabel(x_label)    matplotlib.pyplot.ylabel(y_label)我希望能夠將所有 matplotlib.pyplot.plot() 參數添加到我的新函數中,以便我可以將它們輸入 matplotlib.pyplot.plot() 但不希望手動這樣做(通過添加它們到函數聲明),你會從我在某些情況下已經這樣做的代碼片段中看到。關鍵在于每個新函數都有自己的一組參數,這些參數需要以某種方式與 matplotlib.pyplot.plot() 的參數區分開來。一些在線搜索讓我發現了 Python 裝飾器,但我一直無法找到一個在這種情況下對我有幫助的好例子。我相信在 Python 中有一種簡單的方法可以做到這一點。如果有人可以幫助我,我將不勝感激。
查看完整描述

3 回答

?
MMTTMM

TA貢獻1869條經驗 獲得超4個贊

您可以在函數簽名中使用argsandkwargs并將參數傳遞給plot()函數。有很多很好的解釋來解釋它們是如何工作的,所以我不會在這里重復。


本質上args并kwargs允許您傳遞可變數量的參數。在這種情況下,kwargs它會打包您傳遞給字典中函數的任何“額外”關鍵字參數。然后可以將字典傳遞到接收函數中并使用**kwargs


對于您的功能:


def plot_measurement(x_label, y_label, *args, latex_mode = False, **kwargs):

    # Keyword arguments can be accessed as a normal dictionary

    if (kwargs["label"] == ""):

        kwargs["label"] = self.identifier


    if (latex_mode):

        matplotlib.rc("text", usetex = True)

        matplotlib.rc("font", family = "serif")


    matplotlib.pyplot.plot(*args, **kwargs)

    matplotlib.pyplot.xlabel(x_label)

    matplotlib.pyplot.ylabel(y_label)

使用函數參數調用它并添加您需要的任何額外參數plot():


plot_measurement("x_label", "y_label", x, y, latex_mode = False, linewidth = 1, label = "plot_label")

args并將kwargs“吸收”您傳遞給函數的任何額外參數。要使用您的關鍵字參數,請將其放在函數簽名中所有位置參數之后 - 現在包括*args.


完整的工作示例:


import numpy as np

import matplotlib

import matplotlib.pyplot as plt


def plot_measurement(x_label, y_label, *args, latex_mode = False, **kwargs):

    if (kwargs["label"] == ""):

        kwargs["label"] = self.identifier


    if (latex_mode):

        matplotlib.rc("text", usetex = True)

        matplotlib.rc("font", family = "serif")


    plt.plot(*args, **kwargs)

    plt.xlabel(x_label)

    plt.ylabel(y_label)

    plt.show()


x = np.arange(0, 20)

x = np.reshape(x, (4, 5))

y = np.arange(5, 25)

y = np.reshape(y, (4, 5))


plot_measurement("x axis label", "y axis label", x, y, latex_mode = False, color = "red", label = "plot label")

生產:

http://img1.sycdn.imooc.com//63b529f0000145d606070441.jpg

查看完整回答
反對 回復 2023-01-04
?
森林海

TA貢獻2011條經驗 獲得超2個贊

您可以將單個參數字典傳遞給plot_measurement所有位置參數,將第二個參數字典傳遞給所有可選參數,以使事情更簡單。傳統上,這些被稱為args和kwargs(關鍵字參數)。使用 a *as in*args展開一個列表并將每個列表元素作為參數放入函數中;類似地,**展開一個字典并將每個字典鍵值對放入函數中(這對于關鍵字參數很方便)


# also this is standard because it's very convenient

import matplotlib.pyplot as plt


## Examples of how args and kwargs are formatted 


# all required arguments go in a list in order

args = [x,y,format]


# all non-required (keyword) arguments go in a dictionary

kwargs = {

     line_width: 1,

     label: plot_label

     }



def plot_measurement(self,args,kwargs,plot_label,x_label,y_label,latex_mode = False):

    # here all of the args and keyword args are passed together

    # whereas all arguments used directly by plot_measurement are not passed together

    # though they could be for cleanliness


    if (plot_label == ""):

        plot_label = self.identifier


    if (latex_mode):

        matplotlib.rc("text", usetex = True)

        matplotlib.rc("font", family = "serif")


    plt.plot(*args, **kwargs)

    plt.xlabel(x_label)

    plt.ylabel(y_label)


查看完整回答
反對 回復 2023-01-04
?
GCT1015

TA貢獻1827條經驗 獲得超4個贊

對于后代,此響應中發布的代碼不起作用,并且是響應@Derek 和@Erik 的一個小測試用例。


我看不到如何在評論中放置格式化代碼,所以我把它貼在這里。請原諒我的罪過!


def plot_measurement(self, latex_mode = False, *args, **kwargs):

    print("\nlen(args) = {0}, args = {1}".format(len(args), args))

    print("\nlen(kwargs) = {0}, kwargs = {1}\n".format(len(kwargs), kwargs))


    if (latex_mode):

        matplotlib.rc("text", usetex = True)

        matplotlib.rc("font", family = "serif")


    matplotlib.pyplot.plot(*args, **kwargs)

使用以下咒語調用。


test_measurement1.plot_measurement(test_measurement1.data[6], test_measurement1.data[15])

data[6] 和 data[15] 都是 numpy.arrays 并連接在一起。輸出如下:


len(args) = 1, args = (array([-8.21022986e-06, -8.19599736e-06, -8.16865495e-06, ...,

       -7.70015886e-06, -7.70425522e-06, -7.71744717e-06]),)


len(kwargs) = 0, kwargs = {}

還有,代碼錯誤就行了


if (latex_mode):

給出錯誤


ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()



查看完整回答
反對 回復 2023-01-04
  • 3 回答
  • 0 關注
  • 236 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號