python - 绘制图形时出现尺寸错误
问题描述
我正在尝试在 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
.
解决方案
在函数 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())
推荐阅读
- html - 如何以三种不同的方式对齐弹性项目?
- docker - docker-compose 在不运行命令的情况下启动/启动
- reactjs - onClick 发布请求并重定向到另一个页面
- regex - 删除 Atom 中现有文件的尾随换行符
- python - PostgreSQL。如何使用python复制一行中单元格的值并将其粘贴到同一表中另一行的另一个单元格中
- c# - AutoMapper - 具有多个相同类型属性的 ProjectTo 类
- php - 来自数据库的php数据不显示
- javascript - 显示进度条
- sql - 当字段为空时从 SQL 数据透视表中删除行
- json - 如何使用 Django DRF 将“CSV 杂乱数据”转换为“JSON 结构化数据”