matplotlib - 通过** kwargs传递行参数时出错

时间:2015-03-04 18:40:03

标签: python matplotlib

我有一个绘制线条的函数,类似的东西:

def tmp_plot(*args, **kwargs):
    plt.plot([1,2,3,4,5],[1,2,3,4,5], *args, **kwargs)

当我通过将行作为关键字参数传递来调用它时:

tmp_plot(line = '-')

我收到此错误:

TypeError: set_lineprops() got multiple values for keyword argument 'line'

但它可以使用颜色参数。

我使用matplotlib 1.4.3和python 2.7.7

任何线索?

2 个答案:

答案 0 :(得分:3)

您可以在下面的Traceback中看到Matplotlib在哪里添加自己的line参数。这意味着您自己的关键字参数与Matplotlib在set_lineprops调用中拥有的关键字参数重复:

In [1]: import matplotlib.pyplot as plt
In [2]: plt.plot([1,2,3], [1,4,9], line='-')
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-82-f298702afcfe> in <module>()
----> 1 plt.plot([1,2,3], [1,4,9], line='-')

/Users/xnx/anaconda/envs/py33/lib/python3.3/site-packages/matplotlib/pyplot.py in plot(*args, **kwargs)
   2985         ax.hold(hold)
   2986     try:
-> 2987         ret = ax.plot(*args, **kwargs)
   2988         draw_if_interactive()
   2989     finally:

/Users/xnx/anaconda/envs/py33/lib/python3.3/site-packages/matplotlib/axes.py in plot(self, *args, **kwargs)
   4137         lines = []
   4138 
-> 4139         for line in self._get_lines(*args, **kwargs):
   4140             self.add_line(line)
   4141             lines.append(line)

/Users/xnx/anaconda/envs/py33/lib/python3.3/site-packages/matplotlib/axes.py in _grab_next_args(self, *args, **kwargs)
    317                 return
    318             if len(remaining) <= 3:
--> 319                 for seg in self._plot_args(remaining, kwargs):
    320                     yield seg
    321                 return

/Users/xnx/anaconda/envs/py33/lib/python3.3/site-packages/matplotlib/axes.py in _plot_args(self, tup, kwargs)
    305         ncx, ncy = x.shape[1], y.shape[1]
    306         for j in range(max(ncx, ncy)):
--> 307             seg = func(x[:, j % ncx], y[:, j % ncy], kw, kwargs)
    308             ret.append(seg)
    309         return ret

/Users/xnx/anaconda/envs/py33/lib/python3.3/site-packages/matplotlib/axes.py in _makeline(self, x, y, kw, kwargs)
    257                             **kw
    258                             )
--> 259         self.set_lineprops(seg, **kwargs)
    260         return seg
    261 

TypeError: set_lineprops() got multiple values for argument 'line'

在任何情况下,您的意思是lslinestyle而不是line

In [83]: plt.plot([1,2,3], [1,4,9], ls='-')
Out[83]: [<matplotlib.lines.Line2D at 0x10ed65610>]

答案 1 :(得分:0)

我猜想matplotlib的内部结构除了调用者提供的参数外,还解压缩参数的内部字典,而不删除重复项,因此你和matplot lib内部都通过两条并行路由提供相同名称的单独关键字参数。