Py学习  »  Python

用python绘制带有2个参数的函数的绘图

Алекс Серкин • 7 年前 • 2048 次点击  

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

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: get_plot() takes exactly 2 arguments (3 given)
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/43982
文章 [ 1 ]  |  最新文章 7 年前
Sheldore David Zwicker
Reply   •   1 楼
Sheldore David Zwicker    7 年前

除了函数名中的拼写错误外,在完成所有函数的追加之后,还应将列表转换为for循环之外的数组。此外,我不明白为什么你可以让代码这么复杂,当你只能在你的NUMPY数组上使用矢量化操作。 xs 作为 ys=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