pythonmatplotlibplotparametric-equations

Butterfly Curve with all the folds of the wings of different levels have different colors


enter image description here
I have plotted the Butterfly curve with the following code:

def butterfly_curve(timestamps):
    x=np.zeros(timestamps.size)
    y=np.zeros(timestamps.size)
    
    for k in range(0,timestamps.size):
        x[k] = np.sin(timestamps[k])*(np.exp(np.cos(timestamps[k]))-2*np.cos(4*timestamps[k])-(np.sin((timestamps[k]/12)))**5)
        y[k] = np.cos(timestamps[k])*(np.exp(np.cos(timestamps[k]))-2*np.cos(4*timestamps[k])-(np.sin((timestamps[k]/12)))**5)
    
    return x, y

time = np.arange(0, 12 * np.pi, 0.01)
plt.plot(butterfly_curve(time)[0],butterfly_curve(time)[1])
plt.xlabel('x')
plt.ylabel('y')
plt.axhline(0, color='black')
plt.axvline(0, color='black')
plt.title('Butterfly Curve')

plt.show()

Can anyone tell me how I could achieve that all the folds of the wings of different levels have different colors?


Solution

  • enter image description here

    Your code is complicated and inefficient, the function can be written simply as

    In [8]: def butterfly_curve(t):
       ...:     c, s = np.cos(t), np.sin(t)
       ...:     r = (np.exp(c)-2*np.cos(4*t)-(np.sin((t/12)))**5)
       ...:     return s*r, c*r
    

    Next, to plot the "folds" with different colors you can use a variation on the following (I don't know what is a "fold"), possibly changing ① the no. of iterations, ② the length of the first interval and ③ the additive constant at the end of the loop

    In [9]: fig, ax = plt.subplots()
       ...: t = np.linspace(0, np.pi, 301)
       ...: for n in range(12):
       ...:     ax.plot(*butterfly_curve(t))
       ...:     t += np.pi
    

    (note that you don't need to call the function two times, the * as a unary prefix operator is the unpack operator).