繁体   English   中英

包装 function 用于 matplotlib.pyplot.plot

[英]Wrapper function for matplotlib.pyplot.plot

我是 Python 的相对新手(但在许多其他语言方面经验丰富。)并且正在编写 Python 脚本来处理科学测量数据。

我最终得到了许多 class 函数,每个函数都调用 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() 但不希望手动这样做(通过添加它们到 function 声明),您将从该代码片段中看到我在某些情况下已经这样做了。 关键是每个新的 function 都有自己的一组参数,这些参数需要以某种方式与 matplotlib.pyplot.plot() 的参数区分开来。

在网上进行了一些搜索后,我发现了 Python 装饰器,但在这种情况下我找不到一个可以帮助我的好例子。 我确信在 Python 中有一种简单的方法可以做到这一点。

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

您可以在 function 签名中使用argskwargs并通过 arguments 传递给plot() function。 很多很好的解释来解释它们是如何工作的,所以我不会在这里重复一遍。

本质上argskwargs允许您传递可变数量的 arguments。 kwargs的情况下,它会打包任何“额外”关键字 arguments 您传递给字典中的 function。 然后可以在接收 function 内部传递字典并使用**kwargs解包

对于您的 function:

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)

使用 function arguments 调用它,并为plot()添加任何额外的 arguments :

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

argskwargs将“吸收”您传递给 function 的任何额外 arguments。 要使用您的关键字参数,请将其放在 function 签名中的所有位置 arguments 之后 - 现在包括*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")

生产: 在此处输入图像描述

扩展@Dr。 V 的评论,您可以将单个参数字典传递给plot_measurement ,其中所有位置为 arguments,第二个参数为所有可选 arguments,以使事情更简单。 传统上,这些被称为argskwargs (关键字 args)。 *args中使用*展开列表并将每个列表元素作为参数放入 function; 同样, **展开一个字典并将每个字典键值对放入 function (便于关键字参数)

# 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)

对于后代,此响应中发布的代码不起作用,并且是响应@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 并连接在一起。 Output 如下:

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()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM