首页 > 解决方案 > 绘制图形时出现尺寸错误

问题描述

我正在尝试在 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.

标签: pythonmatplotlibgraph

解决方案


在函数 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()) 

推荐阅读