【问题标题】:Getting dimension error when plotting graph绘制图形时出现尺寸错误
【发布时间】:2021-03-02 17:50:20
【问题描述】:

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

【问题讨论】:

    标签: python matplotlib graph


    【解决方案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()) 
    

    【讨论】:

    • 谢谢,完全错过了我忘记括号了。
    猜你喜欢
    • 2022-07-27
    • 1970-01-01
    • 1970-01-01
    • 2018-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-16
    相关资源
    最近更新 更多