简体   繁体   中英

Python while loop replaces variable

if it runs, the figures should print out one by one. k = [3, 4, 5, 6, 2.1, 3.8, 5.5, 7.2] [![enter image description here][1]][1]

but mine figures overwrites each other. so there has to be break or something? [![enter image description here][2]][2]


from matplotlib import pyplot as plt
import numpy as np

def funcx(t, k, r):
    x_1= r(k-1)np.cos(t)
    x_2= r(np.cos((k-1)t))
    x = x_1 + x_2
    return x 
def funcy(t, k, r):
    y_1= r(k-1)np.sin(t)
    y_2= rnp.sin((k-1)t)
    y = y_1 - y_2
    return y 

def plot_function(k, r, string_plot):
    plt.figure()
    plt.plot(x_list, y_list, string_plot)
    ax = plt.subplot()
    ax.axis('off')
    plt.show()


k = [3, 4, 5, 6, 2.1, 3.8, 5.5, 7.2]
r = 5
x_list =[]
y_list=[]



for i in range(0, len(k)):
    for t in np.arange(0, 20*np.pi, 0.001): 
        x_list.append(funcx(t, k[i], r))
        y_list.append(funcy(t, k[i], r))
    plot_function(x_list, y_list, "b")


[![enter image description here][3]][3]


  [1]: https://i.stack.imgur.com/qF3wR.png
  [2]: https://i.stack.imgur.com/t5rS3.png
  [3]: https://i.stack.imgur.com/lmyLL.png

this is how it should be: https://en.wikipedia.org/wiki/Hypocycloid

plot_function(x_list, y_list, "b") it's getting overwritten because of the name given to it "b".

Do this changes to your code. Not sure if it is what you need.

import numpy as np

def funcx(t, k, r):
    x_1= r*(k-1)*np.cos(t)
    x_2= r*(np.cos((k-1)*t))
    x = x_1 + x_2
    return x 
def funcy(t, k, r):
    y_1= r*(k-1)*np.sin(t)
    y_2= r*np.sin((k-1)*t)
    y = y_1 - y_2
    return y 

def plot_function(xlist, ylist,k,ax):
    ax[i].plot(x_list, y_list)
    ax[i].set_title(f'k = {k}')
    ax[i].axis('off')

    #plt.plot(x_list, y_list, string_plot)
    #ax = plt.subplot()
    #plt.axis('off')


k = [3, 4, 5, 6, 2.1, 3.8, 5.5, 7.2]
r = 5
x_list =[]
y_list=[]

#Initialize the subplots before the for loop to avoid the overwriting.
fig, ax = plt.subplots(1,len(k),**{'figsize':(20,4)}) 

for i in range(0, len(k)):
    for t in np.arange(0, 20*np.pi, 0.001): 
        x_list.append(funcx(t, k[i], r))
        y_list.append(funcy(t, k[i], r))
    plot_function(x_list, y_list,k[i],ax)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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