给出了两个论点,但提出了三个论点

时间:2015-12-29 07:56:26

标签: python numpy matplotlib

代码:

import numpy as np 
import matplotlib.pyplot as plt
l2_penalty = np.logspace(1, 7, num=13)
plt.xscale('log',l2_penalty)

我收到错误消息:

TypeError: set_xscale() takes exactly 2 arguments (3 given)

为什么,我只给出了两个论点?

2 个答案:

答案 0 :(得分:2)

查看plot.xscale文档。它是一个绑定方法,因此一个位置arg是self。另一个是像' log'这样的词。所有其他args都需要一个关键字。'

set_xscale是一个axes方法,它采用相同的参数。 plot方法可能会委托给axes方法。

答案 1 :(得分:0)

plt.xscale的通话签名为xscale(*args, **kwargs),但在文档中,通话签名实际为plt.xscale(scale, **kwargs)

调用该函数时,所有未命名的参数(通过*args传入)都会在内部传递给另一个函数。然后,您提供的每个未命名参数都会被扩展出来,因此(例如):

def xscale(*args, *kwargs):
    # Do some stuff
    first_argument = 10

    # Call another function taking only 2 arguments
    other_function(first_argument, *args)
    # This expands to: other_function(first_argument, 'log',l2_penalty)
    # And since the target only takes 2 arguments and you provided 3
    # It is this internal call that causes an error.

    # Probably do some other stuff...

在寻求帮助调试这些问题时,在SO上提供完整的堆栈跟踪非常重要。我不得不自己运行你的代码,我希望它产生与你相同的错误,但我没有受让人......

Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
  File "/usr/lib64/python2.7/site-packages/matplotlib/pyplot.py", line 1502, in xscale
    ax.set_xscale(*args, **kwargs)
TypeError: set_xscale() takes exactly 2 arguments (3 given)

如果要向plt.xscale函数传递其他参数,则需要将它们作为命名参数传递,并按照文档进行操作:

    'log'

        *basex*/*basey*:
           The base of the logarithm

        *nonposx*/*nonposy*: ['mask' | 'clip' ]
          non-positive values in *x* or *y* can be masked as
          invalid, or clipped to a very small positive number

        *subsx*/*subsy*:
           Where to place the subticks between each major tick.
           Should be a sequence of integers.  For example, in a log10
           scale: ``[2, 3, 4, 5, 6, 7, 8, 9]``

           will place 8 logarithmically spaced minor ticks between
           each major tick.

以下示例可能使用命名参数:

plt.xscale('log', basex=10, basey=5)
plt.xscale('log', subsx=[2, 3, 4])