绘制给定函数定义的图

时间:2019-02-06 21:01:40

标签: python matplotlib

我目前正在尝试绘制python中某个函数的迭代图。我已经定义了如下函数,但是我不确定如何绘制图形,以使y值位于y轴上,而迭代次数位于x轴上。

因此,我尝试将plt.plot函数的x值用作不同的值,但将logistic(4, 0.7)作为y轴的y值。

def logistic(A, x):
    y = A * x * (1 - x)
    return y

但是每个返回一个错误。任何人都可以阐明这一点,我希望进行总共1000次迭代。

2 个答案:

答案 0 :(得分:0)

当您向我们展示函数 logistic(4,0.7)时,我对您所说的x是重复次数并不太了解。据我所知,迭代是整数,整数。您不能只进行一半或部分迭代

def logistic(A, x):
    y = A * x * (1 - x)
    return y

A = 1

x_vals = []
y_vals = []

for x in range(1,1000):
    x_vals.append(x)
    y_vals.append(logistic(A,x))
    #plt.plot(x_vals,y_vals) # See every iteration
    #plt.show()
plt.plot(x_vals,y_vals) # See all iterations at once
plt.show()

答案 1 :(得分:0)

啊,后勤图。您是否要绘制蜘蛛网图?如果是这样,您的错误可能在其他地方。正如其他人提到的那样,您应该发布错误消息和代码,以便我们更好地为您提供帮助。但是,根据您给我们的信息,您可以使用numpy.arrays来获得所需的结果。

import numpy as np
import matplotlib.pyplot as plt

start = 0
end = 1
num = 1000

# Create array of 'num' evenly spaced values between 'start' and 'end'
x = np.linspace(start, end, num)

# Initialize y array
y = np.zeros(len(x))

# Logistic function
def logistic(A, x):
    y = A * x * (1 - x)
    return y

# Add values to y array
for i in range(len(x)):
    y[i] = logistic(4, x[i])

plt.plot(x,y)
plt.show()

但是,使用numpy.arrays,您可以省略for循环而只需

x = np.linspace(start, end, num)
y = logistic(4, x)

,您将获得相同的结果,但速度更快。

相关问题