简体   繁体   English

使用 Python 绘制蝴蝶曲线

[英]Plotting Butterfly Curve using Python

I have been trying to plot a butterfly curve with python and this is my code.我一直在尝试用 python 绘制蝴蝶曲线,这是我的代码。

import math
r = np.arange(0, 2, 0.01)
theta = 2 * np.pi * r
r_of_theta=math.exp(np.sin(theta))-2*np.cos(4*theta)+sin((2*theta-np.pi)/24)**5
t_of_theta.astype(int)
ax = plt.subplot(projection='polar')
ax.plot(theta,t,color='blue')
ax.set_rticks([0.5, 1, 1.5, 2]) 
ax.set_rlabel_position(-22.5)
plt.show()

But I keep getting this error但我不断收到此错误

TypeError                                 Traceback (most recent call last)
<ipython-input-66-876098af4358> in <module>()
      2 r = np.arange(0, 2, 0.01)
      3 theta = 2 * np.pi * r
----> 4 r_of_theta=math.exp(np.sin(theta))-2*np.cos(4*theta)+sin((2*theta-np.pi)/24)**5
      5 t_of_theta.astype(int)
      6 ax = plt.subplot(projection='polar')

TypeError: only size-1 arrays can be converted to Python scalars

Can someone help me out?有人可以帮我吗? Thanks in advance.提前致谢。

Look, you had a couple of typing errors.看,你有几个打字错误。 You should use np.你应该使用np. everywhere.到处。

import numpy as np
import matplotlib.pyplot as plt

r = np.arange(0, 2, 0.01)

theta = 2 * np.pi * r
r_of_theta = []
r_of_theta = np.exp(np.sin(theta[:]))-2*np.cos(4*theta[:])+np.sin((2*theta[:]-np.pi)/24)**5
r_of_theta.astype(int)

ax = plt.subplot(projection='polar')
ax.plot(r_of_theta,color='blue')
ax.set_rticks([0.5, 1, 1.5, 2]) 
ax.set_rlabel_position(-22.5)
plt.show()

math.exp works on a single value, and you're giving it an array. math.exp处理单个值,并且您给它一个数组。 You can vectorize the function using np.vectorize , though:不过,您可以使用np.vectorize对函数进行矢量化:

import math
r = np.arange(0, 2, 0.01)
theta = 2 * np.pi * r
vec_exp = np.vectorize(math.exp)
r_of_theta=vec_exp(np.sin(theta))-2*np.cos(4*theta)+np.sin((2*theta-np.pi)/24)**5

Now your code will run until at least that line.现在您的代码将至少运行到该行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM