matplotlib.pyplot.plot 的包装函数

我是 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 中有一种简单的方法可以做到这一点。


如果有人可以帮助我,我将不胜感激。


胡说叔叔
浏览 320回答 3
3回答

MMTTMM

您可以在函数签名中使用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 npimport matplotlibimport matplotlib.pyplot as pltdef 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")生产:

森林海

您可以将单个参数字典传递给plot_measurement所有位置参数,将第二个参数字典传递给所有可选参数,以使事情更简单。传统上,这些被称为args和kwargs(关键字参数)。使用 a *as in*args展开一个列表并将每个列表元素作为参数放入函数中;类似地,**展开一个字典并将每个字典键值对放入函数中(这对于关键字参数很方便)# also this is standard because it's very convenientimport matplotlib.pyplot as plt## Examples of how args and kwargs are formatted # all required arguments go in a list in orderargs = [x,y,format]# all non-required (keyword) arguments go in a dictionarykwargs = {     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)

GCT1015

对于后代,此响应中发布的代码不起作用,并且是响应@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()
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python