在下面的程序中,我试图将圆心连接到圆周上 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 新手,请多多包涵。
最佳答案
plot()
命令的 x 和 y 元素需要具有相同数量的元素。替换行
plt.plot([0, x1], [0, y1], color='gray')
具有以下内容:
plt.plot([np.zeros(60,), x1], [np.zeros(60,), y1], color='gray')
关于python - Numpy linspace 和绘图,ValueError : an array element with a sequence,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37953090/