绘制函数图的 Python 函数

标签 python function plot

我目前正在尝试在 python 中定义一个绘制函数的函数。

我已经完成了这个:

def plota_f(x0, xf, n):
  xpoints = []
  ypoints = []
  for i in range(0,n):
      xpoints.append(x0+(xf-x0)/n *i)
      ypoints.append(np.sin(x0+(xf-x0)/n *i))
  plt.plot(xpoints, ypoints)
  plt.show()

绘制从 x0 到 xf 的 Sin 函数,共 n 个步骤,但我希望能够添加参数 f

def plota_f(f,x0,xf,n):

这样我就可以打电话了

plota_f(x**2,0,10,100)

并绘制二次函数或调用

plota_f(np.sin(x),0,10,100)

并绘制正弦函数。有没有简单的方法可以做到这一点?


编辑:这是我在回答后得到的代码

def plota_f(f,x0,xf,n):
xpoints = []
ypoints = []
for i in range(0,n):
    xpoints.append(x0+(xf-x0)/n *i)
    x=x0+(xf-x0)/n *i
    ypoints.append(eval(f))
plt.plot(xpoints, ypoints)
plt.show()

最佳答案

使用 numpy 非常简单:

from x0 to xf with n steps

这是np.linspace的定义

be able to add a parameter f

使用 lambda 函数

演示:

def plota_f(f, x0, xf, n):
    # Use with caution, eval can be dangerous
    xpoints = np.linspace(x0, xf, n, endpoint=True)
    ypoints = eval(f)
    plt.plot(xpoints, ypoints)
    plt.show()

plota_f('x**2', 0, 10, 100)

enter image description here

关于绘制函数图的 Python 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70974321/

相关文章:

javascript - 在 document.write 中运行函数,其中 document.write 在 window.open 中

c - 如何使用c语言显示用户输入的5个数字的总和

r - 大面积绘制 igraph

python - 如何在 matplotlib 中为等高线图创建图例?

python - 为我的计算值制作字典

python - Gurobi Python API : model. addVars() 太慢

Python 列表删除问题

python - Pandas:针对时间序列数据生成直方图/数据透视图

function - 什么是多态λ?

使用 mtext 删除添加到绘图中的文本