Reputation: 73
I have been trying to plot a butterfly curve with python and this is my code.
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.
Upvotes: 2
Views: 2996
Reputation: 1455
Look, you had a couple of typing errors. You should use 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()
Upvotes: 2
Reputation: 6132
math.exp
works on a single value, and you're giving it an array. You can vectorize the function using np.vectorize
, though:
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.
Upvotes: 1