在Python中为带有两个参数的函数绘制图

时间:2019-02-16 14:51:29

标签: python numpy matplotlib plot

我需要绘制一个间隔上定义的简单函数的图。

import numpy as np
from matplotlib import pylab as plt

def sqr(x, n=2):
    return float(x ** n)

def get_plot(func, xs, n):
    ys = []
    for x in xs:
        ys.append(func(x, n))
        ys = np.array(ys)
    plt.plot(xs, ys)

xs = np.arange(1.0, 30., 0.01)
get_plot(sqr, xs, 4)

但这给了我typeError:

TypeError: get_plot() takes exactly 2 arguments (3 given)

1 个答案:

答案 0 :(得分:0)

除了函数名称中的拼写错误外,一旦添加完所有函数,就应该将列表转换为for循环之外的数组。此外,我不明白为什么只对NumPy数组xsys=xs**4那样使用向量化操作

import numpy as np
from matplotlib import pylab as plt

def sqr(x, n=2):
    return float(x ** n)

def get_plot(func, xs, n):
    ys = []
    for x in xs:
        ys.append(func(x, n))
    ys = np.array(ys) # <-- moved outside the for loop
    plt.plot(xs, ys)

xs = np.arange(1.0, 30., 0.01)
get_plot(sqr, xs, 4)

enter image description here