Numpy linspace和plotting,ValueError:带有序列的数组元素

时间:2016-06-21 19:33:24

标签: python numpy

我试图在下面的程序中将60条线连接到圆周中的60个不同的等间距点,

import matplotlib.pyplot as plt
import numpy as np

figure = plt.figure(figsize=(10, 10))

theta = np.linspace(0, 2 * np.pi, 60)
r = 3.0
x1 = r * np.cos(theta)
y1 = r * np.sin(theta)

plt.plot(x1, y1, color='blue')
plt.plot([0, x1], [0, y1], color='gray')

plt.axis([-4, 4, -4, 4])
plt.grid(True)

figure.tight_layout()
figure.savefig('test.png', facecolor='white', edgecolor='black')

它出现以下错误,

$ python test.py
Traceback (most recent call last):
  File "test.py", line 12, in <module>
    plt.plot([0, x1], [0, y1], color='gray')
  File "/usr/lib/pymodules/python2.7/matplotlib/pyplot.py", line 2987, in plot
    ret = ax.plot(*args, **kwargs)
  File "/usr/lib/pymodules/python2.7/matplotlib/axes.py", line 4137, in plot
    for line in self._get_lines(*args, **kwargs):
  File "/usr/lib/pymodules/python2.7/matplotlib/axes.py", line 317, in _grab_next_args
    for seg in self._plot_args(remaining, kwargs):
  File "/usr/lib/pymodules/python2.7/matplotlib/axes.py", line 288, in _plot_args
    y = np.atleast_1d(tup[-1])
  File "/usr/lib/python2.7/dist-packages/numpy/core/shape_base.py", line 49, in atleast_1d
    ary = asanyarray(ary)
  File "/usr/lib/python2.7/dist-packages/numpy/core/numeric.py", line 512, in asanyarray
    return array(a, dtype, copy=False, order=order, subok=True)
ValueError: setting an array element with a sequence.

如果我使用某个常量值,例如plt.plot([0, 0], [0, r], color='gray')而不是plt.plot([0, x1], [0, y1], color='gray')则可行。似乎numpy.linspace这样的情节是不可能的。

我发现了类似的问题ValueError: setting an array element with a sequence,但没有帮助我。我是python的新手,请耐心等待。

1 个答案:

答案 0 :(得分:2)

ISynchronizeInvoke命令的x和y元素需要具有相同数量的元素。替换

plot()

以下内容:

plt.plot([0, x1], [0, y1], color='gray')

结果如下: enter image description here