NumPy linspace 和绘图,ValueError:数组元素具有序列。

3

我正在尝试在下面的程序中将圆心与圆周上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个回答

2
您的plot()命令中的x和y元素需要具有相同数量的元素。请替换该行。
plt.plot([0, x1], [0, y1], color='gray')

以下是需要的内容:

plt.plot([np.zeros(60,), x1], [np.zeros(60,), y1], color='gray')

结果看起来像这样:enter image description here。这是一个涉及IT技术的图片,我无法对其进行更多解释。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接