我正在尝试在 python 上绘制二次图。但是我遇到了一些问题。
这是我的代码:
import matplotlib
import matplotlib.pyplot as plt
def get_x_squared():
new_list = []
x_values = range(-5,6)
lista = list(x_values)
for number in lista:
new_number = number**2
new_list.append(new_number)
return new_list
def get_quadratic_function():
y_values = get_x_squared
x = list(range(-5,6))
y = y_values
plt.plot(x,y)
plt.xlabel("x-axis")
plt.ylabel("y-axis")
plt.title("Quadratic function")
plt.show()
print(get_quadratic_function())
所以第一个函数 get_x_squared
给了我从 -5 到 5 的平方的 y 值。第二个函数用从 -5 到 5 的 x 值(不是平方)绘制它。但是,我得到的错误消息是 x 和 y 需要具有相同的维度,但是当我打印出 x 和 y 列表时,它们都包含 11 个元素。似乎 get_qudratic_function
无法访问 get_x_squared()
函数的返回值,即使我已将其定义为 y_values
。
答案 0 :(得分:1)
在函数 get_quadratic_function 中更改 y_values = get_x_squared()。所以代码看起来像这样。
import matplotlib.pyplot as plt
def get_x_squared():
new_list = []
x_values = range(-5,6)
lista = list(x_values)
for number in lista:
new_number = number**2
new_list.append(new_number)
return new_list
def get_quadratic_function():
y_values = get_x_squared()
x = list(range(-5,6))
y = y_values
plt.plot(x,y)
plt.xlabel("x-axis")
plt.ylabel("y-axis")
plt.title("Quadratic function")
plt.show()
print(get_quadratic_function())