Python编程,使用matplotlib时出错

时间:2017-05-02 18:47:33

标签: python matplotlib

在ipython notebook中运行此代码时,

import matplotlib.pyplot as pl
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]

plt.plot(x, y)

plt.plot(x, y)

plt.ylabel('Doubles')

我遇到了这些错误:

TypeError                                 Traceback (most recent call last)
<ipython-input-4-f244d65cd40c> in <module>()
      1 x={1,2,3,4,5}
      2 y={2,4,6,8,10}
----> 3 plt.plot(x,y)

/usr/local/lib/python3.5/dist-packages/matplotlib/pyplot.py in plot(*args, **kwargs)
   3315                       mplDeprecation)
   3316     try:
-> 3317         ret = ax.plot(*args, **kwargs)
   3318     finally:
   3319         ax._hold = washold

/usr/local/lib/python3.5/dist-packages/matplotlib/__init__.py in inner(ax, *args, **kwargs)
   1896                     warnings.warn(msg % (label_namer, func.__name__),
   1897                                   RuntimeWarning, stacklevel=2)
-> 1898             return func(ax, *args, **kwargs)
   1899         pre_doc = inner.__doc__
   1900         if pre_doc is None:

/usr/local/lib/python3.5/dist-packages/matplotlib/axes/_axes.py in plot(self, *args, **kwargs)
   1405 
   1406         for line in self._get_lines(*args, **kwargs):
-> 1407             self.add_line(line)
   1408             lines.append(line)
   1409 

/usr/local/lib/python3.5/dist-packages/matplotlib/axes/_base.py in add_line(self, line)
   1791             line.set_clip_path(self.patch)
   1792 
-> 1793         self._update_line_limits(line)
   1794         if not line.get_label():
   1795             line.set_label('_line%d' % len(self.lines))

/usr/local/lib/python3.5/dist-packages/matplotlib/axes/_base.py in _update_line_limits(self, line)
   1813         Figures out the data limit of the given line, updating self.dataLim.
   1814         """
-> 1815         path = line.get_path()
   1816         if path.vertices.size == 0:
   1817             return

/usr/local/lib/python3.5/dist-packages/matplotlib/lines.py in get_path(self)
    987         """
    988         if self._invalidy or self._invalidx:
--> 989             self.recache()
    990         return self._path
    991 

/usr/local/lib/python3.5/dist-packages/matplotlib/lines.py in recache(self, always)
    674                 x = ma.asarray(xconv, np.float_).filled(np.nan)
    675             else:
--> 676                 x = np.asarray(xconv, np.float_)
    677             x = x.ravel()
    678         else:

/usr/local/lib/python3.5/dist-packages/numpy/core/numeric.py in asarray(a, dtype, order)
    529 
    530     """
--> 531     return array(a, dtype, copy=False, order=order)
    532 
    533 

TypeError: float() argument must be a string or a number, not 'set'

我不确定这些错误是什么,为什么会出现这些错误?我使用了Ipython的2和3个python版本,但在这两种情况下都存在类似的错误。我该如何纠正这些错误?感谢

2 个答案:

答案 0 :(得分:2)

错误消息中的代码和发布的代码不匹配。一旦使用方括号[]作为列表,并在回溯中使用花括号{}作为集合。第一种方法是正确的。

答案 1 :(得分:1)

回溯表明您已将变量定义为集合,而不是列表。 plt.plot()函数正在等待列表。

确保在定义变量时使用括号而不是花括号。也就是说,x = [1,2,3,4,5]而非x = {1,2,3,4,5}