【问题标题】:Plotting lambda function绘制 lambda 函数
【发布时间】:2021-10-15 14:59:47
【问题描述】:

我正在尝试绘制一个通过lambda 定义的函数。我总是收到错误消息:

x and y must have the same first dimension but have shapes (20,) and (1,)

但我不知道为什么。

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(-4,8,20)
print(x)
fx = lambda x: x - 10 * np.exp(-1/10*((x-2)**2)) 
plt.plot(x, fx)
plt.show()

【问题讨论】:

    标签: python numpy matplotlib lambda


    【解决方案1】:

    fx 是一个 lambda 函数,x 是一个列表。 您应首先计算所有结果,然后将其传递给绘图:

    x  = np.linspace(-4,8,20)
    fx = lambda x: x - 10 * np.exp(-1/10*((x-2)**2)) 
    y  = [fx(val) for val in x] # Not sure, maybe you need to use Numpy too instead ? Not a expert of Numpy
    
    plt.plot(x, y)
    

    【讨论】:

    • plt.plot(x, fx(x)) 就够了
    • @diggusbickus 由于 lambda 函数正在等待一个数字而不是一个列表,我不确定这会成功吗? x = [1, 2, 3, 4]; fx = lambda x: x+1; y = fx(x) >>TypeError: can only concatenate list (not "int") to list
    • 它是np.array 而不是list
    • 如上所述,不是 Numpy 专家(根本不是)。然后在打算使用数字时传递一个 np 数组?哇。
    • 是的 numpy 就是哇!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-18
    • 1970-01-01
    • 2022-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多