我试图为x ^ 11 + 1 = 0绘制多边形,并且我在矩阵的维度上出错了。矩阵元素是多边形的顶点。代码:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import PolyCollection
n = 11
verticesx = np.empty(shape=0)
for k in np.arange(n):
verticesx = np.append(verticesx, [[np.cos(np.rad2deg((2 * k + 1) / n * np.pi))],
[np.sin(np.rad2deg((2 * k + 1) / n * np.pi))]])
print(verticesx)
plt.subplot(aspect='equal')
plt.xlim(-1.5, 1.5)
plt.ylim(-1.5, 1.5)
circle = plt.Circle((0, 0), 1, color='b', fill=False)
poly = PolyCollection(verticesx, facecolor='r', edgecolor='g', closed=True)
plt.gcf().gca().add_artist(circle)
plt.gcf().gca().add_artist(poly)
错误信息是这一个:
[-0.79263773 -0.6096929 0.38593669 -0.92252527 0.99066117 0.13634679 0.12236983 0.99248457 -0.92787342 0.37289531 -0.59846007 -0.80115264 0.6208046 -0.78396533 0.91699383 0.39890139 -0.15029666 0.98864094 -0.99411079 0.10836856 -0.35977985 -0.93303722] Traceback (most recent call last): File "F:/MISCOSAS/ProgramasPython3/Circunferencia/circunferenciaunidad.py", line 15, in <module> poly = PolyCollection(verticesx, facecolor='r', edgecolor='g', closed=True) File "C:\Anaconda3\lib\site-packages\matplotlib\collections.py", line 867, in __init__ self.set_verts(verts, closed) File "C:\Anaconda3\lib\site-packages\matplotlib\collections.py", line 878, in set_verts if len(xy): TypeError: object of type 'numpy.float64' has no len() Process finished with exit code 1
答案 0 :(得分:1)
import numpy as np
from __future__ import division
import matplotlib.pyplot as plt
from matplotlib.collections import PolyCollection
n = 11
verts = []
k=np.linspace(0,n,1.0)
for k in range(n):
a=360/11/180*np.pi
x= np.cos( k*a )
y= np.sin( k*a )
verts.append((x,y))
# appending to a numpy array works differently than appending to a list
plt.subplot(aspect='equal')
# plt.xlim(-1.5, 1.5)
# plt.ylim(-1.5, 1.5)
circle = plt.Circle((0, 0), 1, color='b', fill=False)
# you need to pass a collection here, not just one polygon, solve that by putting brackets around
poly = PolyCollection([verts], facecolor='r', edgecolor='g', closed=True)
plt.gcf().gca().add_artist(circle)
plt.gcf().gca().add_artist(poly)
plt.xlim(-1, 1)
plt.ylim(-1, 1)
plt.show()