首页 > 解决方案 > 为什么参数不能在 pyplot 中以 x 和 y 的形式显式传递?

问题描述

我正在使用作为 plt 导入的 matplotlib.pyplot 模块进行绘图。

在 plt.plot() 语句中,如果我将参数传递为“x= array1,”y= array2”,我会得到“TypeError: plot got an unexpected keyword argument 'x'”。

如果我简单地传递“array1 和 array2”,代码就会正确执行,而没有明确说明它们对应于 x 和 y 轴。

这是为什么?

标签: pythonmatplotlib

解决方案


如果您查看函数定义,https://github.com/matplotlib/matplotlib/blob/9a24fb724331f50baf0da4d17188860357d328a9/lib/matplotlib/axes/_axes.py#L72,您可以在那里看到星号,并且使用它不会t 使用关键字作为非可选参数。例如,请参阅Python args 和 kwargs:Demystified

def plot(self, *args, scalex=True, scaley=True, data=None, **kwargs):
        """
        Plot y versus x as lines and/or markers.
        Call signatures::
            plot([x], y, [fmt], *, data=None, **kwargs)
            plot([x], y, [fmt], [x2], y2, [fmt2], ..., **kwargs)

推荐阅读