用matplotlib绘制方程式 [英] graphing an equation with matplotlib

查看:46
本文介绍了用matplotlib绘制方程式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一个函数,可以绘制我告诉它的任何公式.

I'm trying to make a function that will graph whatever formula I tell it to.

import numpy as np  
import matplotlib.pyplot as plt  
def graph(formula, x_range):  
    x = np.array(x_range)  
    y = formula  
    plt.plot(x, y)  
    plt.show()  

当我尝试调用它时会发生以下错误,我相信它正在尝试在到达 y = formula 之前进行乘法运算.

When I try to call it the following error happens, I believe it's trying to do the multiplication before it gets to y = formula.

graph(x**3+2*x-4, range(-10, 11))

Traceback (most recent call last):  
  File "<pyshell#23>", line 1, in <module>  
    graph(x**3+2*x-4, range(-10, 11))  
NameError: name 'x' is not defined  

推荐答案

这是因为

graph(x**3+2*x-4, range(-10, 11))

x未定义.

最简单的方法是将要绘制的函数作为字符串传递,并使用 eval 将其作为表达式求值.

The easiest way is to pass the function you want to plot as a string and use eval to evaluate it as an expression.

所以你的代码只需最少的修改就会

So your code with minimal modifications will be

import numpy as np  
import matplotlib.pyplot as plt  
def graph(formula, x_range):  
    x = np.array(x_range)  
    y = eval(formula)
    plt.plot(x, y)  
    plt.show()

你可以称之为

graph('x**3+2*x-4', range(-10, 11))

这篇关于用matplotlib绘制方程式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆